String.format bug in HTML5 application

I get an error in the HTML5 bundled application when I call string.format with a table argument after the format string. The table has a __tostring metatmethod so it should convert to a string and it works as expected when running from the editor. But in the bundled application in causes an error as string.format complains about being given a table when expecting a string.

HTML5 use Lua 5.1.4 while all other platforms use LuaJIT. I bet there is some subtle difference where the __tostring metamethod isn’t invoked in this case…

3 Likes

Yep:

> lua -v
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio

> cat foo.lua
local t = setmetatable({}, {
	__tostring = function(t, ...)
		return "Hello" .. 123
	end
})

print(t)
print(string.format("Testing %s", t))%

> lua foo.lua 
Hello123
lua: foo.lua:8: bad argument #2 to 'format' (string expected, got table)
stack traceback:
	[C]: in function 'format'
	foo.lua:8: in main chunk
	[C]: ?
2 Likes

I came back to say that I tested it and you are right. Interesting to know…

A quick hack to give better behaviour:

function log(f, ...)
	local args = { ... }
	for i, v in ipairs(args) do
		if type(v) == "table" then
			args[i] = tostring(v)
		else
			args[i] = v
		end
	end

	print(string.format(f, unpack(args)))
end

I do more in my log function but just in case anybody else hits this problem this shows one way to work around it.

1 Like

Also discussed here: __tostring and string.format and Incompatibility with Lua 5.1: __tostring/tostring/print · Issue #351 · LuaJIT/LuaJIT · GitHub