Roblox问题:数值变量大于0时for循环仍不执行
Lua For循环不执行问题解决
问题描述
我有一个for循环,本应根据大于0的数值变量值执行对应次数。尝试直接调用getItemNumber()方法而非赋值给变量后,循环仍不运行。谷歌搜索结果多为while循环内容,与我的for循环问题不符。
相关代码如下:
if getItemNumber() > 0 then local numb = 0 --This will be the price after the loop local loopNumb = getItemNumber() for i=10, loopNumb, 10 do --I start with i=10 and it executes for each items and increments by 10 everytime so it will add the loopNumb number times 10 for the price because 1 item = 10 money. (sorry for being difficult to understand) print(i) --I need to print to check if the loop executes, it does not. numb += loopNumb * 10 end print(numb) --more code but not related to the problem and I need this loop for the code after. end
getItemNumber()函数代码:
function getItemNumber() : number local currString = script.Parent.Parent.NumberOfItemsTxt.Text local currNumb = tonumber(currString) if currNumb ~= nil then print("valid") return currNumb else print("nil") return 0 end end
注:该循环位于GUI元素(TextButton)的点击事件中,脚本为LocalScript,并非嵌套循环。
问题原因
Lua的数值for循环语法是for 变量=起始值, 结束值, 步长 do,只有满足以下条件时循环才会执行:
- 若步长为正数:起始值 ≤ 结束值
- 若步长为负数:起始值 ≥ 结束值
假设getItemNumber()返回的物品数量是N(比如3、5这类小于10的数),你写的for i=10, loopNumb, 10中,起始值10大于结束值loopNumb,且步长为正,循环直接跳过,自然不会执行任何代码。
另外从你的注释看,你想计算总价(1个物品=10钱),但当前循环里的numb += loopNumb *10逻辑也有问题——这会让总价变成loopNumb * loopNumb *10,而不是预期的loopNumb *10。
解决方案
根据你的需求调整循环逻辑即可:
方案1:执行loopNumb次循环(每次累加10)
如果需要循环loopNumb次来实现后续逻辑,同时计算正确总价:
local itemCount = getItemNumber() if itemCount > 0 then local numb = 0 -- 循环itemCount次,每次加10 for i=1, itemCount do print("循环次数:", i) numb += 10 end print("总价:", numb) -- 后续代码 end
方案2:按10的倍数递增到总价(若需要遍历10、20...总价的过程)
如果需要循环中输出10、20...直到总价:
local itemCount = getItemNumber() if itemCount > 0 then local numb = 0 local totalPrice = itemCount * 10 -- 从10开始,每次加10,直到总价 for i=10, totalPrice, 10 do print("当前累加值:", i) numb = i -- 或者根据需求做其他操作 end print("总价:", numb) -- 后续代码 end
额外提示
建议在if判断前先调用一次getItemNumber()并把值存到变量里,避免重复调用函数读取UI文本,提升效率同时避免潜在的数值变化问题。
内容的提问来源于stack exchange,提问作者Error404
相关产品推荐
相关产品推荐

