lua尾调用实践
简述:数据驱动+尾调用 实现的一个找房子游戏
笔记: table构造时,表内元素仅取当前外部值(即不会随外部值改变而改变);如果想存储一个函数,函数应已被定义。
--@author blanc 2018/3/27
local move_key = {
a = "left",
d = "right",
s = "down",
w = "up",
}
----------------------------------------
--map
--
--
-- room2--room3
-- | |
-- room1--room4
-- |
-- room5
--
-----------------------------------------
local func_t = {} --函数列表
local player = {} --玩家
player.runTo = function (room)
print("i am run to " ..(room or "em...."))
end
local room_about = {
room1 = {
map = {right = "room4", up = "room2"},
},
room2 = {
map = {right = "room3", down = "room1"},
},
room3 = {
map = {left = "room2", down = "room4"},
},
room4 = {
map = {left = "room1", down = "room5", up = "room3"},
},
room5 = {
map = {up = "room4",},
},
}
local step_num = 0
local key_list = {"a", "s", "w", "d", "w", "d", "a", "s", "w", "d", "a", "d", "d", "w", "d", "d", "s", "a", "w", "d"}
local function getRoomNameByKey(form_room)
player.runTo(form_room)
--获得下一步
step_num = step_num + 1
if step_num > #key_list then return "gameOver" end
key = key_list[step_num]
-- print(debug.traceback())
local conect_room = room_about[form_room].map[move_key[key]]
if nil == func_t[conect_room] then
return form_room
else
return conect_room
end
end
func_t.gameOver = function ()
return print("is_end")
end
local function main()
--创建5个房间
for i = 1, 5 do
func_t["room" .. i] = function ()
return func_t[getRoomNameByKey("room" .. i)]()
end
end
func_t.room1()
end
main()