I've been working with Lua for a little bit, and I have finally come up with some code that can be extended to create the core of a game model. I come from an object oriented background, so working with Lua is very different for me.
The purpose of this code would be to create the game model for a game with Lua. Another programming language would load the scripts and then make the calls to create the Game object and to advance the turns. Any information resulting from a game turn could be passed back to the rendering in the proper programming language.
I would love to hear about any aspect of this code, but I am new to Lua syntax so I am sure I am making rookie mistakes.
Game.lua
--This syntax loads other scripts, such as Player.lua
local player = require "Player"
local Game = {} -- the table representing the class, which will double as the metatable for the instances
Game.__index = Game -- failed table lookups on the instances should fallback to the class table, to get methods
-- syntax equivalent to "MyClass.new = function..."
function Game.new()
local self = setmetatable({}, Game)
self.players = {}
self.currentTurn = 0
return self
end
--Adding players to the game
function Game.addPlayers(self, numPlayers)
--i has to be set to 1 for it to work properly
for i = 1, numPlayers, 1 do
self:addPlayer()
end
end
function Game.addPlayer(self)
table.insert(self.players, player.new(6))
end
--Advancing and reporting the game turns
function Game.advanceTurn(self)
self.currentTurn = self.currentTurn + 1
end
function Game.getTurnNumber(self)
return self.currentTurn
end
--test function to access player data
function Game.reportPlayers(self)
for key,value in pairs(self.players) do
print(key)
end
end
--create the game "instance"
local game = Game.new()
game:addPlayers(2)
--these types of commands would be sent to Lua by a proper programming language
game:advanceTurn()
print(game:getTurnNumber())
game:advanceTurn()
print(game:getTurnNumber())
game:reportPlayers()
Player.lua
Player = {} -- the table representing the class, which will double as the metatable for the instances
Player.__index = Player -- failed table lookups on the instances should fallback to the class table, to get methods
-- syntax equivalent to "MyClass.new = function..."
function Player.new(startingHandSize)
local self = setmetatable({}, Player)
self.handSize = startingHandSize
print(self.handSize)
return self
end
function Player.set_handSize(self, newHandSize)
self.handSize = newHandSize
end
function Player.get_handSize(self)
return self.handSize
end
return Player
self.currentTurn
exceedsself.numPlayers
. And while we are here, what is the significance of6
ingame.addPlayer
? Are you having some specific game in mind? – vnp Aug 19 '14 at 0:17