When writing a Lua-facing function in C, what's a good way to check if an argument supports table-like lookups? -


here's potential pattern can check if argument table:

int my_fn(lua_state *l) {   lual_checktype(l, 1, lua_ttable);   // .. stuff table .. } 

this works whenever first argument table. however, other lua types support table lookups, such userdata, , in luajit, cdata.

is there nice way check if table lookup, such via lua_getfield, succeed before call it? mean without restricting type tables. relatedly, tables, userdata, , cdata types in luajit support indexed lookups?

i'm interested in answers restricted lua 5.1 c api because i'm using luajit works version.

clarification

the advantage of lual_checkxxx functions that, in 1 line, they:

  • throw informative, user-friendly error message if type wrong, and
  • provide c-friendly return value can used immediately.

i'm looking similar tables. don't expect c-friendly hash-table return value, do want same quality of error message user if argument in question not indexable.

i'm embracing philosophy of duck typing. if write function wants index keys argument, don't care if argument table, or userdata supports __index lookups. want accept either one.

in general, tables have lookups because it's type defines property. userdata opaque, host knows or adds metatable (which can analyzed) specific behaviour. cdata part of lua compiling luajit, never used type c api (is supported?). @ end have check type/metatable possible lookups , request field check setting, there's no way around lua_getfield (but raw access should faster, see lua_rawget). exception check table array length lua_objlen.

furthermore cheaper solution type checking lua_is*** functions.


Comments