Skip to main content

Extension methods

Attach C# extension methods to the extended type’s Lua instance methodTable so you can write obj:ExtFoo(...). Authoritative: 13-EXTENSION-METHODS.

There is no global scan for ExtensionAttribute. The model is extended type → list of extension classes; those classes are reflected when that type is Bound.

Configuration

ApproachUsage
You can edit the extended type’s sourcePut [LuaExtension(typeof(FooExt), …)] on the extended type
Third-party / precompiled typesSettings luaExtensionXmlPaths + root element ZLuaExtensions

Do not put [LuaExtension] on the extension class (that would require scanning every assembly to discover extensions).

using ZLua;

public static class TransformExt
{
public static void ResetLocal(this UnityEngine.Transform t)
{
t.localPosition = UnityEngine.Vector3.zero;
}
}

[LuaExtension(typeof(TransformExt))]
public class PlayerView : MonoBehaviour { }
<?xml version="1.0" encoding="utf-8"?>
<ZLuaExtensions version="1">
<Assembly name="UnityEngine.CoreModule">
<Type fullName="UnityEngine.Transform">
<Extension assembly="Assembly-CSharp" fullName="MyGame.TransformExt"/>
</Type>
</Assembly>
</ZLuaExtensions>

For the same extended type, Attribute and XML extension-class lists are unioned. Binding T also collects [LuaExtension] from base types.

Il2Cpp: XML is written into static tables at Generate time; the Player does not read XML (re-Generate after changes).

Lua usage

local t = go.transform
t:ResetLocal() -- 冒号;底层是静态扩展方法

Filter rules: public static methods on the extension class that have ExtensionAttribute, whose first parameter can accept the extended type (including this Base for Derived). Open generic extensions are not supported.

Same name as an instance method

Extensions and real instance methods compete in the same overload group; there is no “instance wins” rule. Disambiguate with full-signature keys or [LuaAlias]. See Method overloads.

Common mistakes

SymptomCause
obj:Foo is nilExtension class not configured on the extended type (or base); or Il2Cpp not re-Generated
Only Ext.Foo(obj) worksNot wired as static-as-instance / not in IMT (implementation must follow Spec §4)
Wrong overload calledMerged competition; use full-signature keys or Alias
Attribute on the extension class has no effectDiscovery only scans [LuaExtension] on the extended type

Learning path

PreviousLuaAlias
NextCommon zlua APIs