如何使用索引在Lua中进行计算?

我想写一个函数,但不知道如何实现。

local data ={
[100000000] ='string1',
[250000000] ='string2',
[500000000] ='string3',
}

local calc = 780325665

我想计算calc和数据的每个索引,例如

result= calc-(500000000+250000000)

我喜欢奖励结果和data \ [500000000 ],data \ [250000000 ] = string1和string2

local calc=780325665
for ind,i in pairs(data) do
    repeat
        if calc<0 then return end
        print(calc,data[ind])
        calc=calc-ind
    until calc<ind
end

它不起作用,我希望像我的示例一样

##我希望有人能帮我。

我想创建一个函数,用于计算总数中有多少个官方支付金额。这些数字应返回给我。例如。我有10,25,50和总数380

所以385=(7*50)+(3*10)剩余5

local calc=780325665 -仅示例数字
所以我有100000000,250000000,500000000和总数calc

calc-(500000000+250000000)剩余30325665,因为没有更小的数字

根据它可以缩短多少次,我将奖励那2个数字

点赞
用户2744663
用户2744663

我不确定你想要做什么,但是尝试这样做:

1. 消除 "repeat""until calc<ind"
2."if calc <0" 改为 "if calc<ind"

也许你能添加更多的例子吗?

2013-09-10 03:47:17
用户1548504
用户1548504

如果我理解你的问题正确的话-下面的代码应该适合你-

local data ={
[1]='string1',
[2]='string2',
[10]='string4',
[25]='string3',
}

-- lets get the indices in their increasing order
local indices = {}
for n in pairs(data) do table.insert(indices, n) end
table.sort(indices, function(a, b) return a > b end)

local calc = 97
local result = {}

-- for every index, highest coming first
for _,v in ipairs(indices) do
    -- if calc is bigger than this index
    while calc >= v do
        -- if this index has never been encountered, set it to 1 or add 1 to previous
        result[v] = (result[v] or 0) + 1
        -- reduce calc and check again
        calc = calc - v
    end
end

-- result is your output

如果这不是你正在寻找的,请编辑你的问题以提供更多细节。可能带有一个例子。

2013-09-10 06:30:29
用户2679394
用户2679394

如果你正在尝试对一个表格中的所有数字进行计数和计算,那么这段代码可能会有帮助:

local count = 0
for k, v in pairs(data) do
     count = count + 1
end

local total = 0
for i = 1, count do
   total = total + data[i]
end

这段简单的代码可以帮助你对表格中所有数字进行计数和计算。

2013-09-10 09:55:57