lua-users home
lua-l archive

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


>  Are you reading this as email or through a website?  Because email 
clients
>offset a "respond" option that should keep the post in the 
current thread.

Yes, I'm using a stupid webmail client. I can't do 
else.

>  Here's a simple example.  It's in C, not Pascal, but it does 
illustrate...

Thank you all for you help, this example was perfect. 
Finally I went the full userdata way. Tables could do well too, but use 
slightly more lua memory (circa 3K vs 2K).

First I create my 
metatable:

  luaL_newmetatable(L, 'xplcmetatable');
  lua_pushstring
(L, '__index');		// cell key
  lua_pushcfunction(L, xl_getxtable);	// 
cell value, my handler
  lua_rawset(L, -3); 				// Stores the pair in 
the table

(the last 3 lines are repeated for every needed method). 
Then, for every table to expose:

	p := lua_newuserdata(L, sizeof
(pointer));
	ppointer(p)^ := pointer(xEnviron);
	luaL_setmetatable(L, 
'xplcmetatable');
	lua_setglobal(L, 'env');

The first line creates a 
lua userdata and returns the address of the reserved memory; the second 
line writes to that memory the address of my structure; then the 
metatable is linked to the userdata, and finally a name is given to the 
userdata.

The handler for method __index is like this:

  if lua_gettop
(L)<>2 then exit;	// test not strictly required
  st := lua_tostring(L, 
2);		// field to be accessed
  ptr := lua_touserdata(L, 1);       // 
get the reserved memory for this userdata
  ptr := PPointer(ptr)
^;              // get what I wrote inside it (address of my structure)


  result := 1;      // one value will be returned on the stack
  if 
ptr=pointer(xEnviron) then begin
	lua_pushstring(L, xEnviron[st]);
	
exit
  end;

The last 4 lines are repeated for every table (5 in total 
for now).
The "not required" test is not required because there is no 
way for lua code to reach this handler without passing the correct 
parameters.
The tests "if ptr=...." would be also not required for the 
same reason, a typecast could be used to deploy the pointer directly.


Have a nice day, best regards,
Linuxfan