سؤال

what would be the command to fill a text with a few variables.

ex> "Day: %1 is the %2th day in the %3th week"

where %1 could be 5 , %2 could be 10 and %3 12

in another text it could be: ex> "in the %3 week the %2th day is your Day: %1"

while always the %1 get variable 1, %2 variable 2 and %3 variable 3

i hope i made it understandable :)

its about my Language File and about grammer the variables would sit sometimes at different possitions.

thanks chris

هل كانت مفيدة؟

المحلول

Lua's built-in "fill a text with a few variables" function is string.format, which works like C's printf family of functions.

You can write one that works they way you want by using gsub to find all instances of %n, grab the n and use that to look up one of your arguments by position:

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

Now you can have your place holders refer to arguments by position:

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                               

نصائح أخرى

If you are willing to use placeholder names rather than numbers, you could do this:

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

You can use any pattern you want, like you could use {} instead of (), just change the pattern string accordingly. You could also use numbers but then the table is not as easy to write because the keys have to be strings, so you need cumbersome brackets:

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

You could define a function that adds a metatable that convert string key to number, then you could drop the key entirely, something like this:

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})  )

But in that case you might as well hide such details

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}  )
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top