Lua指向合并3个函数

时间:2016-04-18 11:19:29

标签: lua

如何创建指针,以便我可以创建1个函数而不是3个函数? 我的功能类似于:

for a,b in pairs(places3) do
    char3.moveObject(b[1]) 
end

有没有办法做那样的事情?

for i=1,3,1 do
    for a,b in pairs(places+i) do
        char+i.moveObject(b[1]) 
    end
end

2 个答案:

答案 0 :(得分:1)

您不必为三个表实现三个功能。只需实现一个带表的函数并调用它三次。

类似的东西:

function move(places, char)
  for _, place in pairs(places) do
    char.moveObject(place)
  end
end

然后简单地调用

move(places1, char1)
move(places2, char2)
move(places3, char3)

或将所有字符和地点放入表格

places = {places1, places2, places3}
chars = {char1, char2, char3}

for i, char in ipairs(chars) do
  move(places[i], char)
end

有很多方法。

答案 1 :(得分:0)

假设您有以下内容:

local places1 = { some data }
local places2 = { some data }
local places3 = { some data }

local char1 = some table with a moveObject() function
local char2 = some table with a moveObject() function
local char3 = some table with a moveObject() function

然后我会这样做:

-- create pairs of char and places
local char_place_pairs = {
    { char = char1, places = places1 },
    { char = char2, places = places2 },
    { char = char3, places = places3 },
}

-- iterate over the pairs and per pair call the moveObject function for each entry in places
for _,char_place_pair in pairs(char_place_pairs) do
    for a,b in pairs(char_place_pair.places) do
        char_place_pair.char.moveObject(b[1]) 
    end
end