Last active
May 28, 2018 14:48
-
-
Save max1220/c21cdc086ad54f51111c to your computer and use it in GitHub Desktop.
Adds implied string formats to lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Makes the module operator (%) between a string and a table behave like string.format | |
-- This works by setting the string metatable __mod function. | |
-- Example use: | |
-- str = "Hello %s, %d as hexadecimal is 0x%.2X" % {"world", 127, 127} | |
local mt = getmetatable("") | |
assert(mt, "string has no metatable") | |
mt.__mod = function(a,b) | |
if (type(a) == "string") and (type(b) == "table") then | |
return a:format(unpack(b)) | |
else | |
return error("attempt to perform arithmetic on a string value") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment