[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: cpp to lua binding question
- From: "Peter Shook" <pshook@...>
- Date: Mon, 26 May 2003 10:09:32 -0400
Hi Georges,
setmetatable returns its first argument. I didn't realize that the manual
no longer mentions this.
This is an omission in the new manual. Perhaps this is intentional?
setmetatable is just the Lua 5 version of the old settag function. The old
manual says: settag returns the value of its first argument (the table).
Sometimes the manual doesn't tell you the whole story.
When you really want to know how something works, have a look at the code in
src/lib/lbaselib.c
static int luaB_setmetatable (lua_State *L) {
int t = lua_type(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected");
if (luaL_getmetafield(L, 1, "__metatable"))
luaL_error(L, "cannot change a protected metatable");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1;
}
The return 1 is a giveaway that it returns something. The settop(L, 2)
leaves only the arguments on the stack. Then lua_setmetatable(L, 1) pops
the metatable off the stack, so only the original table is left on top of
the stack and that is what is returned by 'setmetatable'.
By the way, this is a better implementation of Class. There is no sense in
creating a new metatable for each new object; it's better to keep the one
metatable as an upvalue/closure value.
local function Class(methods, mt)
methods = methods or {}
mt = mt or {__index = methods}
function methods:new(obj)
return setmetatable(obj or {}, mt)
end
return methods
end
Sorry for leaving out the semicolons and parentheses. This probably makes
more sense to you:
cc = cs.texture.t1;
print('cc', cc);
cc:load('one');
cc = cs.mesh.m2;
print('cc', cc);
cc:load('two');
Cheers,
- Peter
Georges Mertens wrote:
Feel your function : 'function Class(methods)' will help me with OO in
Lua.
My question : what is the efect of :
return setmetatable(obj or {}, {__index = methods})
What is the value of 'setmetatable' which is returned. Thought
'setmetatable' sets second argument as metatable for the first argument,
but no retun value.
Also : have a problem with the syntax of the statements at the end. See a
lot of white spaces but no '()'
cc = cs.texture.t1 print('cc',cc) cc:load'one'
cc = cs.mesh.m2 print('cc',cc) cc:load'two'
cc = cs.sound.s3 print('cc',cc) cc:load'three'
cc = cs.sound.s1 print('cc',cc) cc:load'four'
Would you be so kind to shed some light ...
Thank you very much for your kind attention.
Best Regards,
Georges.
_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*
http://join.msn.com/?page=features/junkmail