lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Soni L. once stated:
> 
> 
> On 23/06/15 03:19 PM, Rena wrote:
> >On Tue, Jun 23, 2015 at 2:11 PM, Soni L. <fakedme@gmail.com> wrote:
> >>
> >>On 23/06/15 03:09 PM, Sean Conner wrote:
> >>>It was thus said that the Great Luiz Henrique de Figueiredo once stated:
> >>>>>>co = coroutine.create(function() print"test" end)
> >>>>>>...
> >>>>>>Can we get a thread metatable?
> >>>>>debug.setmetatable(co,{__len=function(thread) return "abc" end})
> >>>>>print(#co) --> abc
> >>>>I think the OP wants
> >>>>         debug.setmetatable(co,{__index=coroutine})
> >>>>so that he can say co:resume().
> >>>    Or
> >>>
> >>>         debug.setmetatable(
> >>>                 co,
> >>>                 {
> >>>                   __call = function(co,...)
> >>>                     return coroutine.resume(co,...)
> >>>                   end
> >>>                 }
> >>>         )
> >>>
> >>>so that we can say
> >>>
> >>>         co()
> >>>
> >>>    -spc
> >>>
> >>>
> >>And how do you get the status with that?
> >>
> >>Not co:status(), that wouldn't work...
> >>
> >>
> >>--
> >>Disclaimer: these emails are public and can be accessed from <TODO: get a
> >>non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.
> >>
> >>
> >By using both __call and __index.
> >
> __call and co() makes it look like a function call, which may be kinda 
> confusing. On the other hand OOP syntax co:resume() is more Lua-like, as 
> strings have it too. You also cannot index functions.

  Yes you can.

	function foo(x)
	  return 3 * x + 5
	end

	mt =
	{
	  __index = function(obj,idx)
	    local d = string.dump(obj)
	    return d:sub(idx,idx)
	  end
	}
	
	debug.setmetatable(foo,mt)  
	
	print(foo[3])  
	print(mt.__index[3])

  Granted, this is just a proof-of-concept that simply returns back the
bytecode for a function, but it's easy enough to do other things, say,
return upvalues, local variables, parameters, actual instructions (a byte
index of 3 here returns 'u', part of the Lua signature for a dumped
function:

00000000: 1B 4C 75 61 51 00 01 04 08 04 08 00 07 00 00 00 .LuaQ...........
00000010: 00 00 00 00 40 79 2E 6C 75 61 00 04 00 00 00 06 ....@y.lua......
00000020: 00 00 00 00 01 00 02 04 00 00 00 4E 00 00 80 4C ...........N...L
00000030: 40 C0 00 5E 00 00 01 1E 00 80 00 02 00 00 00 03 @..^............
00000040: 00 00 00 00 00 00 08 40 03 00 00 00 00 00 00 14 .......@........
00000050: 40 00 00 00 00 04 00 00 00 05 00 00 00 05 00 00 @...............
00000060: 00 05 00 00 00 06 00 00 00 01 00 00 00 02 00 00 ................
00000070: 00 00 00 00 00 78 00 00 00 00 00 03 00 00 00 00 .....x..........
00000080: 00 00 00                                        ...

the actual instructions are further in).  

  -spc (Will do Stupid Lua Tricks for food 8-)