Re: __tostring does not work with complex
- From: Evan Wies <evan@xxxxxxxxxxxxx>
- To: luajit@xxxxxxxxxxxxx
- Date: Thu, 23 Jul 2015 11:45:26 -0400
On 07/23/2015 06:29 AM, Laurent Deniau wrote:
Hi,
Here is a small example that does not work as expected (?) where
numtostring is never called and It works with other data.
Best,
Laurent.
As a workaround, one can wrap the complex with a struct and give that
ctype/cdata a metatable implementing __tostring.
Below is a reworked example...
-Evan
local ffi = require 'ffi'
local M = {}
M.format = "%- 10.4f"
local function numtostring (x)
io.write('numtostring called with ', x,'\n')
return string.format(M.format, x)
end
function M.__tostring (x)
if x.c.im == 0 then return numtostring(x.c.re)
elseif x.c.re == 0 then return
string.format('%si', numtostring(x.c.im))
elseif x.c.im < 0 then return string.format('%s%si',
numtostring(x.c.re),numtostring(x.c.im))
else return
string.format('%s+%si',numtostring(x.c.re),numtostring(x.c.im))
end
end
local c_t = ffi.metatype('struct { complex c; }', M)
print(c_t(3i))
io.write(tostring(c_t(3i)),'\n')
Other related posts: