Re: __tostring does not work with complex

  • From: Laurent Deniau <Laurent.Deniau@xxxxxxx>
  • To: "<luajit@xxxxxxxxxxxxx>" <luajit@xxxxxxxxxxxxx>
  • Date: Thu, 23 Jul 2015 16:55:07 +0000

Hi,

On Jul 23, 2015, at 5:45 PM, Evan Wies <evan@xxxxxxxxxxxxx> wrote:



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…

Instead of wrapping the entire complex module that would make the interface
with C cumbersome, I have overridden tostring to include complex number (and
other cdata) formatting. I need to do it anyway to control the formatting of
the numbers and the complex numbers.

local M = {}
local g_tostring = tostring
local M.format = "%g"
function M.tostring (x)
return type(x) == 'number' and string.format(M.format, x) or x.tostring and
x:tostring() or g_tostring(x)
end
return M

then complex module implements M.tostring()

Best,
Laurent



-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: