lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

This doesn't seem to work in my code, but I wanted a sanity check - am I trying to do something illegal in Lua?

I want to create a fulluserdata, but assign a Lua table to it as metatable (mt1), and in turn assign a C++ created metatable (mt2) to the first (mt1)
Essentially, I want to be able to interact with a fulluserdata as if it were a table by treating mt1 as a proxy, and yet still inherit class methods from C functions in mt2.

The problem is that the userdata does not seem to be looking up values in the metatable mt1 - can anyone see what I'm doing wrong?

pseudocode:

registerClass {
luaL_newmetatable(L, classname)
luaL_openlib(L, NULL, methods, 0)
}

newInstance {
lua_newtable(L); // mt1

// create a test value
lua_pushstring(L, "half")
lua_pushnumber(L, 0.5)
lua_settable(L, -3) // mt1.half = 0.5

void * udata = (void *)lua_newuserdata (L, sizeof(void *));
udata = new Object();

// duplicate userdata at index 1 for returning later
lua_pushvalue(L, -1)
lua_insert(L, 1)

// udata.mt = mt1
lua_setmetatable(L, -2);

// get class metatable (mt2)
luaL_getmetatable(L, classname)
lua_setmetatable(L, -2); // mt1.mt = mt2


// remove mt1 from stack
lua_settop(L, 1)

// return userdata to Lua
return 1
}

Lua:

a = Class() -- calls newInstance in C
print(type(a)) -- userdata 
print(a.half) -- should print 0.5 by finding "half" in the metatable mt1, but triggers an error:

PANIC: unprotected error in call to Lua API: attempt to index global 'a' (a userdata value))

Why isn't my table mt1 acting as metatable to the lua object?

Thanks in advance!