Question

Let's say we have a table that was passed to a function and it's now on top of the stack like so:

// -1 = table

Is it possible to get the metatable from that table on stack? I can simply get it with a known-name identifier like so:

luaL_getmetatable(L, "Foo");

But I want to re-use the function and get the metatable from the table that's in the stack.

There is probably an easy way to do this, but I can't seem to find a function for this.

Était-ce utile?

La solution

Use lua_getmetatable rather than luaL_getmetatable. The lua_ version is equivalent to getmetatable() in Lua, i.e. it gets the metatable from a value on the stack. The luaL_ version is for looking up (by name) metatables registered earlier with luaL_newmetatable.

In your case, it would just be:

// push the table
lua_getmetatable(L, -1);
// table is still on the stack at -2
// its metatable on top of it at -1

Note that lua_getmetatable() returns 1 and pushes the metatable if the value has one, and returns 0 and pushes nothing if it doesn't have a metatable - rather than pushing nil as, for example, lua_getglobal does.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top