lua-users home
lua-l archive

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


Hi,

I have some code to access a C array from lua, and got it to work
following the example code around pg. 246 of the lua book (1st edition).
If I register the metamethods from the lua side, everything works,
but when I tried to register them in the luaopen_array() function, I got
an 'attempt to index a string value' error.  This occurs if  I say

> require 'array'

 -- but not if I say

> package.loadlib('./array.so','_luaopen_array')()

Without going into full detail, luaopen_array() bombs in the
4th line below:

  lua_pushstring(L, "__index");
  lua_pushstring(L, "get");
  lua_gettable(L, 2);           // get array.get
  lua_settable(L, 1);           // array_mt.__index = array.get

The reason for the crash is that the stack is empty when called by
loadlib(), but has one entry ("array") when called by require().
This is easily fixed by indexing from the top of the stack:

  lua_pushstring(L, "__index");
  lua_pushstring(L, "get");
  lua_gettable(L, -3);          // get array.get
  lua_settable(L, -4);          // array_mt.__index = array.get

but I think this counts as a bug.  Do I get a reward?  I only got
my lua book a few weeks ago, only to find it was already obsolete.

Can I get a discount on the 2nd edition?  ;)

rob