Skip to content

Instantly share code, notes, and snippets.

@max1220
Last active May 28, 2018 14:48
Show Gist options
  • Save max1220/c21cdc086ad54f51111c to your computer and use it in GitHub Desktop.
Save max1220/c21cdc086ad54f51111c to your computer and use it in GitHub Desktop.
Adds implied string formats to lua
-- 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