从连续表中获取特定值

时间:2014-11-25 21:10:13

标签: lua

尝试允许连接表如此引用:

local group = table.concat(arguments, ",", 1)

其中arguments = {" 1,1,1"}

目前,正在做group[2]给我逗号。如何在仍然允许两位数的情况下避免这种情况?

(我尝试使用它的片段)

for i = 1, #group do target:SetGroup(i, tonumber(group[i])) end

2 个答案:

答案 0 :(得分:0)

也许你想要像

这样的东西
local i = 1
for v in string.gmatch(s, "(%w+),*") do
   group[i] = v
   i = i + 1
end

修改版本以回应评论,完全避开表格:

local i = 1
for v in string.gmatch(s, "(%w+),*") do
   target:SetGroup(i, tonumber(v))
   i = i + 1
end

答案 1 :(得分:0)

拆分功能(你必须将它添加到代码中)

split = function(str, delim)
    if not delim then
        delim = " "
    end
    -- Eliminate bad cases...
    if string.find(str, delim) == nil then
        return { str }
    end
    local result = {}
    local pat = "(.-)" .. delim .. "()"
    local nb = 0
    local lastPos
    for part, pos in string.gfind(str, pat) do
        nb = nb + 1
        result[nb] = part
        lastPos = pos
    end
    -- Handle the last field
    result[nb + 1] = string.sub(str, lastPos)
    return result
end

所以

local arguments = {"1,1,1"};
local group = split(arguments[1], ",");

for i = 1, #group do
    target:SetGroup(i, tonumber(group[i]))
end

还要注意

local arguments = {"1,1,1"};
local group = split(arguments[1], ",");
local group_count = #group;

for i = 1, group_count do
    target:SetGroup(i, tonumber(group[i]))
end

是更快的代码;)