Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why isn't my string printing properly with using string.format?

Asked by 6 years ago
Edited 6 years ago

Hi!

I'm attempting to format a string using the text [[ ]] thing. I have come across unexpected behavior that I don't know how to solve.

local a = [[Potatos = %s
Carrots = %s
]] -- This is a multi-line text.

string.format(a, "YES", "NO") -- Format the a string with string.

print(a)

-- Result:
-- Potatos = %s
--Carrots = %s

--Expected result:
-- Potatos = YES
-- Carrots = NO

How would I get this to print like this? I've looked at so many wiki articles and nothing seems to be working.

Thanks, Nathan.

1 answer

Log in to vote
2
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
6 years ago
Edited 6 years ago

Your problem is that you aren't updating the 'a' variable. String functions will not update the environment for you, you have to redefine it yourself.

local a = [[Potatos = %s
Carrots = %s
]]

a = string.format(a,"YES","NO")
print(a)

This can be shortened as well.

print(tostring([[Potatoes = %s
Carrots = %s]]):format("YES","NO"))
1
(Minor) To be even shorter, you can take out the word 'tostring' (though you still need the parentheses). It should end with a newline to be consistent with the string block, though chess123mate 5873 — 6y
0
Fantastic answer! Thank you very much, can't believe it was that simple. WelpNathan 307 — 6y
Ad

Answer this question