2
votes

Is it possible to push a function as a property in Lua?

Right now, I can have Get/Set functions by pushing them as fields like so:

lua_pushcfunction(L,L_Getter);
lua_setfield(L, -2, "GetValue");    

lua_pushcfunction(L,L_Setter);
lua_setfield(L, -2, "SetValue");    

And calling them in Lua like so:

MyObject:SetValue("NewValue")

Is it possible to push a property that's mapped to a C function without metatables? I could map __index and __newindex in metatable to a custom function but I was wondering if there is an easier way. Ultimately, I want the following syntax without metatables:

MyObject.CValue = 1
print(MyObject.CValue)

Is this possible without __index and __newindex?

1
Have you tried it? It should just work. Provided MyObject is a table.lhf
@lhf Yep, it just returns function: 00XXXXXX which makes sense since that field is mapped to a function.Grapes
@lhf It's a table with a metatable that points __index to various fields of a userdata.Grapes

1 Answers

3
votes

Without metatables? No. Metamethods are the only way to invoke a function to evaluate tbl.foo. You could make MyObject a userdata, but again you need a metatable to provide the __index metamethod.

Learn to love metatables. They are the backbone of C/Lua integration.