lua-users home
lua-l archive

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


I am new to Lua. I need to design an implementation which includes both OO design (single inheritance) and some form of "sandboxing" to prevent global variable clutter for use in a video game. After a few hours looking through the online docs and experimenting with some scripts I am leaning in the direction described below. I am hoping someone with some experience could take a moment and see if I am on the right track.

First, my "system" defines a base class along these lines...

ObjectMaster = {}
function ObjectMaster:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end

function ObjectMaster:func1 (v)
self.var = v
-- etc.
end

function ObjectMaster:Event1Happened(v)
self.e1 = getgametime()
-- etc.
end


--etc
The above code is pretty much "textbook" from the "Programming in Lua" book section 16 on OO programming.

Then... the system's users would derive their own types from that base. Each type would be in a file that would something like this...

DerivedObject = ObjectMaster:new{}

DerivedObject._envrionment = {}
setfenv(1, DerivedObject._envrionment)

-- marker 1

-- override base classes' func1...
function DerivedObject:func1(v)
  self.var = v * 2.0
end

The code above is close to what I see in the docs in section 15 on packages. Once these derived classes are "declared" the system will "spawn instances" of these user classes by creating globals of the derived type from the C++ side.

There are two things I am hoping to accomplish with this scenario, and I am hoping someone can let me know if I am on the right track.

1) I think that this will "sandbox" user classes so that the global variable space will not get cluttered. This is accomplished with the setfenv near the top of the file where the user defines his derived class. My hope is that now, if the creator of the derived class inserts a "global" variable declaration at comment "marker 1" above it will go into the "local" environment.

2) I need to be able to easily cleanup these user classes / sandboxes to be sure all memory is freed. I think that in this scenario I will be able to easily clean up / unload user classes by setting all instances of the derived type to nil and the "definition" to nil. So... if I did this...

Obj1DerivedFromDerivedObject  = nil
Obj2DerivedFromDerivedObject  = nil
DerivedObject = nil

... the garbage collector would eventually completely clean up the user's "object definition" and its instances.

I hope I've been able to describe that correctly. I'd be very grateful if any LUA experts could comment on the approach.

Thanks,
Buzz


Never miss a thing. Make Yahoo your homepage.