Re: __tostring does not work with complex

  • From: Simon Schick <demwizzy@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Thu, 23 Jul 2015 13:29:16 +0200

Hey,

I'm not entirely sure but maybe this
<http://luajit.org/ext_ffi_api.html#ffi_metatype> applies here?

"Note that pre-defined operations on types have precedence..."

As a workaround you can get the complex metatable via debug.getmetatable
and set your custom tostring function there:

debug.getmetatable(3i).__tostring = function(x) return "something" end
=tostring(3i)
something


On 23 July 2015 at 12:29, Laurent Deniau <Laurent.Deniau@xxxxxxx> 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.


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.im == 0 then return numtostring(x.re)
elseif x.re == 0 then return string.format('%si',
numtostring(x.im))
elseif x.im < 0 then return string.format('%s%si', numtostring(x.re
),numtostring(x.im))
else return string.format('%s+%si',numtostring(x.re
),numtostring(x.im))
end
end

ffi.metatype('complex', M)

print(3i)
io.write(tostring(3i),'\n')


--
Laurent Deniau http://cern.ch/mad
Accelerators Beam Physics mad@xxxxxxx
CERN, CH-1211 Geneva 23 Tel: +41 (0) 22 767 4647


Other related posts: