Lua / Corona 字符串文本

如何用几个变量填充文本的命令。

例如:"Day: %1 是第 %2 天第 %3 周"

其中,%1 可以是 5,%2 可以是 10,%3 可以是 12。

在另一段文本中可以是:

例如:"在第 %3 周,第 %2 天是你的 Day: %1"

%1 始终获取变量 1,%2 获取变量 2,%3 获取变量 3。

这涉及到我的语言文件和变量的语法,有时变量可能位于不同的位置。

谢谢。

克里斯

点赞
用户501459
用户501459

Lua中内置的“用几个变量填充文本”的函数是string.format,它类似于C语言的printf系列函数

您可以编写一个自己所需的函数,通过使用gsub查找所有实例的%n,获取n并使用该位置查找一个参数:

function format(fmt, ...)
    local args = {...}
    return (fmt:gsub('%%(%d)', function(i) return args[tonumber(i)] end))
end

现在,您可以使占位符按位置引用参数:

format("Day: %1 is the %2th day in the %3th week", day, weekday, week)     --> Day: 22 is the 2th day in the 3th week
format("in the %3 week the %2th day is your Day: %1", day, weekday, week)  --> in the 3 week the 2th day is your Day: 22
format("%1 %2 %3 %2 %1", day, weekday, week)                               --> 22 2 3 2 22
2014-04-18 19:33:16
用户869951
用户869951

如果您愿意使用占位符而不是数字,可以这样做:

message = "Day: %(day) is the %(weekday)th day in the %(week)th week"
print( message:gsub("%%%((%l+)%)", {day='monday', weekday=1, week=5}) )

你可以使用任何模式,比如你可以使用{}而不是(),只需相应地更改模式字符串。你也可以使用数字,但是表不太容易编写,因为键必须是字符串,因此您需要笨重的括号:

message = "Day: %1 is the %2th day in the %3th week"
print( message:gsub("%%(%d+)", {['1']='monday', ['2']=1, ['3']=5})  )

您可以定义一个函数,添加一个元表来将字符串键转换为数字,然后您可以完全删除键,类似于这样:

function str2numKeys(t)
    local mt = {}
    setmetatable(t, mt)
    mt.__index = function(t, k, v) return t[tonumber(k)] end
    return t
end

message = "Day: %1 is the %2th day in the %3th week"
print( message:gsub("%%(%d+)", str2numKeys {'monday', 1, 5})  )

但在这种情况下,您也可以隐藏这样的细节

function string:gsubNum(actuals)
    local function str2numKeys(t)
        local mt = {}
        setmetatable(t, mt)
        mt.__index = function(t, k, v) return t[tonumber(k)] end
        return t
    end

    return self:gsub("%%(%d+)", str2numKeys(actuals))
end

message = "Day: %1 is the %2th day in the %3th week"
print( message:gsubNum {'monday', 1, 5}  )
message = "in the %3 week the %2th day is your Day: %1"
print( message:gsubNum {'monday', 1, 5}  )
2014-04-19 01:19:35