Object-Oriented Design in 3DApps
Discover the fundamentals of object-oriented design in 3D applications using Lua. This guide covers how to define classes, create and use objects, and implement subclassing. Learn how to utilize the `Plant` class, subclass into `Grass`, and implement a custom `tostring` method for displaying object properties effectively. The tutorial also explores dynamic argument passing using `unpack`, allowing for flexible function calls. Perfect for game developers and programmers looking to enhance their coding skills in Lua!
Object-Oriented Design in 3DApps
E N D
Presentation Transcript
Object-Oriented Design in 3DApps Bryan Hickerson Georgia Institute of Technology Kaneva
Defining Classes • Plant = {level = 1, cost = 1, value = 2, xp = 1, type = “Plant”} • function Plant:new(o) • o = o or {} • setmetatable(o, self) • self.__index = self • return o • end • Usage: p = Plant:new() • p = Plant:new{cost = 6, xp 3}
Subclassing • Grass = Plant:new{level = 5, cost = 7, value = 14, type=“Grass”} • function Plant.tostring(o) • local s = “” • s = s..”level=“..o.level..”,” • s = s..”cost=“..o.cost..”,” • s = s..”value=“..o.value..”,” • s = s..”xp=“..o.xp..”,” • s = s..”name=“..o.name • return s • end
Subclassing(continued) g = Grass:new() print(Plant.tostring(g)) Output: “level=5,cost=7,value=14,xp=1,name=Grass” g has none of these values on its own so when they are accessed in the tostring, it looks to Grass to find their values. Grass does not have xp, so it looks to Plant for its value.
tostring() Wouldn’t it be cool to use tostring(g) instead of Plant.tostring(g)? You can do this like so: Plant.__tostring = Plant.tostring This is really convenient for the Luacommandline, because it allows you to do things like “print(g)” and it ‘just works’ Unfortunately, if you do this in a 3DApp, you will get cryptic errors that currently have no workaround
Another way • _tostring = tostring • local function tostring(o) • if not o then return nil end • if o.type == Grass.type then • return Grass.tostring(o) • elseifo.type == SomeClass.type then • return SomeClass.tostring(o) • else • return _tostring(o) • end • end • You can use the same approach to write your own type()
unpack Say we have some function that takes a variable number of arguments such as print or kgp.playersendevent. Then say we also have a list of values, somelist, that is of variable length. How can we pass these values to the above mentioned functions? If the list was always 3 elements we could simply do print(somelist[1], somelist[2], somelist[3]) There is no way to handle the dynamic case in C, but in Lua you can use unpack
unpack(continued) print(unpack(somelist)) unpack simply returns all the elements of somelist at once. Multiple return arguments are formatted in the same way as parameter lists, so this allows us to dynamically generate the input for print