Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua C API - Getting metatable from a table on stack

Tags:

c++

lua

metatable

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.

like image 964
Grapes Avatar asked Sep 27 '13 01:09

Grapes


1 Answers

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.

like image 87
ToxicFrog Avatar answered Sep 25 '22 23:09

ToxicFrog