[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Type Metafield
- From: "Leandro Candido" <enclle@...>
- Date: Sat, 8 Nov 2003 09:19:30 -0200
Hello all,
Well, I don't know if this is already done, but...
Below is a substitute to function "type" IN LUA SIDE, you can replace
either luaB_type in lbaselib.c or in lua, with the script below. This new
type allow you to add a "type metafield"( __type) to be more descriptive,
for example, instead of print( type(acomplexnum) ) --> userdata, the output
is print( type(acomplexnum) ) --> complex.
The old "type" function is now "rawtype". How to do in C ( in file
"lbaselib.c" ):
1) rename luaB_type to luaB_rawtype
2) Copy this before luaB_rawtype:
static int luaB_type(lua_State*L) {
luaL_checkany(L,1);
if( luaL_getmetafield(L,1, "__type" ) == 0) // Get value of __type, 0 ==
no metafield
lua_pushstring(L, lua_typename(L, lua_type(L,1))); file://"raw" type,
same as luaB_rawtype
return 1;
}
3) search for {"type", luaB_type} and add before/after it:
{"rawtype", luaB_rawtype},
4) recompile.
How to do in Lua (WITHOUT adding the above in the C side (lbaselib.c)):
Use this block of code:
-- start of block
rawtype = type
type = function ( var )
local _m = getmetatable(var);
if _m and _m.__type then
return _m.__type;
end
return rawtype(var);
end
-- end of block
Script to test C/Lua:
-- start of block
function Window()
local _w = {}
local _m = { __type = "window" }
setmetatable( _w, _m );
return _w;
end
-- win, here, is a table with metafield __type as "window"
win = Window()
print( rawtype(win) ); --> table
print( type(win) ); --> window
print( "win is a table? ", type(win) == "table" ); --> false
print( "win is a window?", type(win) == "window" ); --> true
print( "But, win is a table?", rawtype(win) == "table" ); --> true
print( "But, win is a window?", rawtype(win) == "window" ); --> false
-- end of block
The
God's Peace,
Leandro.