Lua Metatable Help

Started by
2 comments, last by apefish 13 years, 11 months ago
Is there a way that when I create a Lua metatable in C++, I can index it in some sort of a value(int, string, etc), that later on whenever I find that metatable in another function, I can see if it equals the previous metatable? Please reply if you don't understand. Thanks in advance.
If I asked you for a hundred dollars would the answer to that question be the same as the answer to this question?
Advertisement
If you want to store away the new metatable and then check against it within Lua you can probably use the Lua registry for that.

http://www.lua.org/pil/27.3.1.html

It was made for storing C side constructs in Lua autonomously.

Good Luck!

-ddn
Actually, now I am using the lua_topointer function. Is that better than the registry?
If I asked you for a hundred dollars would the answer to that question be the same as the answer to this question?
Quote:Original post by Matthew Shockley
Is there a way that when I create a Lua metatable in C++, I can index it in some sort of a value(int, string, etc), that later on whenever I find that metatable in another function, I can see if it equals the previous metatable? Please reply if you don't understand. Thanks in advance.


There is a really slick way to do this. You use a thing called the registry, as ddn3 mentioned. There are some functions in the Lua Auxlib that make this quick and easy. The first thing is luaL_newmetatable(L,"name"). This function creates a table (for use as a metatable) in the registry under the name given, it also leaves it on top of the stack. Then you can use luaL_getmetatable(L,"name") to retrieve it later (usually followed by lua_setmetatable(), as part of a constructor). Then you can use luaL_checkudata(L,INDEX,"name") to check if the argument is a userdata with the metatable called "name" in the registry. It throws an error if this is not true. Look at the API reference and PIL to get an idea how these are used.

As for topointer(), dont use it. It is only supposed to be used for debugging, and as a unique value that you can print out (print{} -> Table: 0xb5bc6230 uses topointer). It may not even work as you want, because the gc may relocate, changing the pointer value (it doesn't, but it could).

This topic is closed to new replies.

Advertisement