Upload
susanna-neal
View
215
Download
0
Embed Size (px)
Citation preview
BRYAN HICKERSONGEORGIA INSTITUTE OF TECHNOLOGY
KANEVA
Object-Oriented Design in 3DApps
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
endUsage: 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 Lua commandline, 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 = tostringlocal function tostring(o)
if not o then return nil end if o.type == Grass.type then
return Grass.tostring(o) elseif o.type == SomeClass.type then
return SomeClass.tostring(o) else
return _tostring(o) end
endYou 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