【发布时间】:2022-10-02 17:37:15
【问题描述】:
我目前正在 Roblox 工作室开发一款游戏,我想知道如何在 lua 中将 1k 这样的数字变成 1000?
标签: lua
我目前正在 Roblox 工作室开发一款游戏,我想知道如何在 lua 中将 1k 这样的数字变成 1000?
标签: lua
一个快速的解决方案是使用所有后缀的查找表,例如:
local postfixes = {
["n"] = 10^(-6),
["m"] = 10^(-3),
["k"] = 10^3,
["M"] = 10^6,
["G"] = 10^9,
}
local function convert(n)
local postfix = n:sub(-1)
if postfixes[postfix] then
return tonumber(n:sub(1, -2)) * postfixes[postfix]
elseif tonumber(n) then
return tonumber(n)
else
error("invalid postfix")
end
end
print(convert("1k"))
print(convert("23M"))
print(convert("7n"))
print(convert("7x"))
1000.0
23000000.0
7e-06
invalid postfix
【讨论】: