简体   繁体   中英

Lua C API - Getting metatable from a table on stack

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.

Use lua_getmetatable rather than luaL_getmetatable . The lua_ version is equivalent to getmetatable() in Lua, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM