Created
May 27, 2011 00:50
-
-
Save randrews/994437 to your computer and use it in GitHub Desktop.
First part of an IF system in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Object utilities | |
---------------------------------------- | |
function dispatch(obj, message_name) | |
local m = getmetatable(obj) | |
if not m then return nil end | |
for _, operations in ipairs(m.behaviors) do | |
if operations[message_name] then return operations[message_name] end | |
end | |
return nil | |
end | |
function become(obj, operations) | |
local m = getmetatable(obj) | |
if not m then -- No metatable yet; we'll add one | |
m = {behaviors={}, __index=dispatch} | |
setmetatable(obj, m) | |
end | |
table.insert(m.behaviors, 1, operations) | |
return obj | |
end | |
function new(type, obj) | |
become(obj, type) | |
return obj | |
end | |
-- Room functions | |
---------------------------------------- | |
Room = {} | |
function Room.print_description(room) | |
print(room.name .. "\n\n" .. room.description) | |
end | |
function Room.room_in_dir(room, dir) | |
local name = room.exits[dir] | |
if name then return ROOMS[name] | |
else return nil end | |
end | |
-- All the rooms | |
---------------------------------------- | |
ROOMS = { | |
Kitchen = new(Room, { | |
name = "Kitchen", | |
description = "A simple kitchen.", | |
exits = { w = "LivingRoom" } | |
}), | |
LivingRoom = new(Room, { | |
name = "Living Room", | |
description = "A well-appointed but cluttered living room", | |
exits = { e = "Kitchen", s = "Bedroom" } | |
}), | |
Bedroom = new(Room, { | |
name = "Bedroom", | |
description = "A comfortable bedroom with a well-thumbed book collection", | |
exits = { n = "LivingRoom" } | |
}) | |
} | |
-- Game functions | |
---------------------------------------- | |
Game = {} | |
function Game.input(game, command) | |
for _, rule in ipairs(game.globals) do | |
local message = rule(game, command) | |
if message then | |
return message | |
end | |
end | |
return "Sorry, I didn't understand that" | |
end | |
function Game.add_global(game, rule) | |
table.insert(game.globals, 1, rule) | |
end | |
-- The actual game object | |
---------------------------------------- | |
game = new(Game, { | |
current_room = ROOMS.Bedroom, | |
globals = {} | |
}) | |
game:add_global(function(game, command) | |
if command.verb == "walk" then | |
local new_room = game.current_room:room_in_dir(command.subject) | |
if new_room then | |
game.current_room = new_room | |
return new_room.name .. "\n\n" .. new_room.description | |
else return "There is no exit that way" end | |
end | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment