Beginner LuaPlus Metatables Question
I'm brand new to Lua/LuaPlus and trying to figure out how metatables work.
In this code taken from the manual:
LuaObject metaTableObj = state->GetGlobals().CreateTable("MultiObjectMetaTable");
metaTableObj.SetObject("__index", metaTableObj);
metaTableObj.RegisterObjectFunctor("Print", &MultiObject::Print);
In the first line we create a new table, but the second line is a little confusing. In this table we just created, we are setting the element with key __index equal to the table itself. Why is __index chosen as a key and why set an element of the table to be equal to the table itself?
And then in the next section of code:
MultiObject obj1(10);
LuaObject obj1Obj = state->BoxPointer(&obj1);
obj1Obj.SetMetaTable(metaTableObj);
state->GetGlobals().SetObject("obj1", obj1Obj);
We create a C++ object, associate its address with a LuaObject via the BoxPointer call, and set the metatable so tha开发者_运维问答t we can use the Print function.
But for the last line, is that just creating a global Lua variable called "obj1"? At this point "obj1" and "MultiObjectMetaTable" will be global Lua variables?
This is not standard Lua, it looks like you're using some C++ wrapper that I'm unfamiliar with, but I can make some guesses
In the first line we create a new table, but the second line is a little confusing. In this table we just created, we are setting the element with key __index equal to the table itself. Why is __index chosen as a key and why set an element of the table to be equal to the table itself?
__index
is a special key when using metatables. If I have a table t
and I try to index into it with a key of foo
for example, naturally, I'll get back the value associated with that key. But lets say there's nothing there. Normally if you try to index into a spot that has nothing, you'll get nil
back.
But not if you have a metatable with the special key __index
in it! If you have a metatable with an __index
function or table, it'll use that to find you your value. If you have a table assigned to __index as you do here, it'll look into that table and return the value at the key you provided. This allows you get inheritance-like behavior. i.e. if table t doesn't have this value, default to the value in this other table instead.
But for the last line, is that just creating a global Lua variable called "obj1"? At this point "obj1" and "MultiObjectMetaTable" will be global Lua variables?
As I mentioned, this is not standard Lua, so I'm not totally sure what's happening there. (Mixing C++ and Lua can get tricky though, so while you're still learning Lua it's probably better that you stick to the C interface so you can understand whats really happening. Once you understand that you can move on to more automated solutions)
精彩评论