Sign in to follow this  
Matthew Shockley

Lua Metatable Help

Recommended Posts

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.

Share this post


Link to post
Share on other sites
ddn3    1610
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

Share this post


Link to post
Share on other sites
apefish    176
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).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this