[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Calling a specific function
- From: Nick Trout <Nick.Trout@...>
- Date: Thu, 11 Jul 2002 11:44:14 +0100
> > One way to do it would be by having the file return a table. So in
> > MyObject.lua, you'd do this:
> >
> > ---- MyObject.lua ----
> > return {
> > initialize = function(obj)
> > -- ... stuff ...
> > end
> >
> > TOUCHED = function(obj, args)
> > -- ... stuff ...
> > end
> >
> > -- etc
> > }
> > ----
> >
> > Have your C/C++ code associate the return value of the
> script with the
> > object, then look in the table for the desired handler when an event
> > happens.
>
> Would this work if, for example, the TOUCHED function called
> another utility
> function in the same file?
It depends how you manage your modules. Try reading:
http://www.lua.org/notes/ltn007.html
http://lua-users.org/wiki/NamespacesAndModules
and maybe http://lua-users.org/wiki/ClassesAndMethods
eg. dofile(script) would put foo in the global namespace.
function foo()
-- blah
end
return {
initialize = function(obj)
-- ... stuff ...
end
TOUCHED = function(obj, args)
foo()
end
-- etc
}
eg. dofile(script) would keep foo local to the modules namespace. ie. so you
can avoid naming clashes.
local foo = function ()
-- blah
end
return {
initialize = function(obj)
-- ... stuff ...
end
TOUCHED = function(obj, args)
%foo()
end
-- etc
}
An alternative to the scheme mentioned is to uses "classes". You could tag
them as well for type checking. You could just have the functions to add
them to an aleady existing class.
MyObject = {}
function MyObject:new()
return {}
end
function MyObject:Initialise()
-- do whatever
self.x,self.y = 0,0
end
----
Client code:
dofile("MyObject.lua")
obj = MyObject:new()
obj:Initialise()
print(obj.x,obj.y)
or:
function Handler_new()
return {}
end
function Handler_Initialise()
-- do whatever
self.x,self.y = 0,0
end
function addHandlersToObj(obj)
obj.new = Handler_new
obj.init = Handler_Initialise
end
-- and the client code might work as above
dofile("MyObject.lua")
obj = {}
addHandlersToObj(obj)
obj:Initialise()
print(obj.x,obj.y)
All untested ;-)
Nick