lua-users home
lua-l archive

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


I’m trying to create my own type (for complex numbers) and use it within Lua scripts. It’s okay but the problem is that in some messages this type is denoted as ‘userdata’ which looks ugly. I have found that if type’s metatable has __name field, that it’s value is used as a type name. Unfortunately this key is not used everywhere, e.g. pairs(complex) still uses ‘userdata’ name. Is there a way I can make Lua to use custom type name?

And a second question dedicated to the custom types. Say I have two arrays of luaL_Reg’s: _methods (instance methods) and _meta (metatable with magic methods). _methods array contains methods that are to be called for a particular instance and are used to manipulate it. _meta array contains metamethods (__add, __sub and so on). The problem is related to [] operator, used to index arrays. I use the following code to configure this:

luaL_newmetatable(LUA, "array");
lua_pushstring(LUA, "__name");
lua_pushstring(LUA, "array");
lua_settable(LUA, -3);
luaL_openlib(LUA, nullptr, _meta, 0);
luaL_openlib(LUA, "array", _methods, 0);

lua_pushliteral(LUA, "__index"); 
lua_pushvalue(LUA, -3);  
lua_rawset(LUA, -3); 

lua_pop(LUA, 1);
If use the given code, my __index handler is called, but it is called every time I’m trying to call an instance method of class, for example for:


__index handler is called instead of foo(). If I change the code to (entirely taken from here:

luaL_newmetatable(LUA, SEQ_CLASS"_MT");
luaL_openlib(LUA, SEQ_CLASS, _meta, 0);
lua_pushstring(LUA, "__index");
lua_pushstring(LUA, "get");
lua_gettable(LUA, 2);  /* get seq.get */
lua_settable(LUA, 1);  /* metatable.__index = seq.get */

lua_pushstring(LUA, "__newindex");
lua_pushstring(LUA, "set");
lua_gettable(LUA, 2); /* get array.set */
lua_settable(LUA, 1); /* metatable.__newindex = seq.set */

lua_settop(LUA, top); // clean up

methods are successfully called, but I’m not able to use the [] operator because it returns nil for every key. 

I know that the PIL book contains example of a custom array class, but it shows how to use either OOP-like access (with get() and set() methods) or array-like access (with operators) and I need to combine there two approaches: to have methods and be able to use operators.

I’m using LuaJIT which is almost equal to Lua 5.1.

Best regards