lrotable.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Read-only tables for Lua */
  2. #include <string.h>
  3. #include <lua/lrotable.h>
  4. #include <lua/lua.h>
  5. #include <lua/lauxlib.h>
  6. /* Local defines */
  7. #define LUAR_FINDFUNCTION 0
  8. #define LUAR_FINDVALUE 1
  9. /* Externally defined read-only table array */
  10. extern const luaR_table lua_rotable[];
  11. /* Find a global "read only table" in the constant lua_rotable array */
  12. luaR_result luaR_findglobal(const char *name, lu_byte *ptype) {
  13. unsigned i;
  14. *ptype = LUA_TNIL;
  15. if (strlen(name) > LUA_MAX_ROTABLE_NAME)
  16. return 0;
  17. for (i=0; lua_rotable[i].name; i ++)
  18. if (!strcmp(lua_rotable[i].name, name)) {
  19. *ptype = LUA_TROTABLE;
  20. return i+1;
  21. }
  22. return 0;
  23. }
  24. /* Utility function: find a key in a given table (of functions or constants) */
  25. static luaR_result luaR_findkey(const void *where, const char *key, int type, int *found) {
  26. const char *pname;
  27. const luaL_reg *pf = (luaL_reg*)where;
  28. const luaR_value_entry *pv = (luaR_value_entry*)where;
  29. int isfunction = type == LUAR_FINDFUNCTION;
  30. *found = 0;
  31. if(!where)
  32. return 0;
  33. while(1) {
  34. if (!(pname = isfunction ? pf->name : pv->name))
  35. break;
  36. if (!strcmp(pname, key)) {
  37. *found = 1;
  38. return isfunction ? (luaR_result)(size_t)pf->func : (luaR_result)pv->value;
  39. }
  40. pf ++; pv ++;
  41. }
  42. return 0;
  43. }
  44. int luaR_findfunction(lua_State *L, const luaL_reg *ptable) {
  45. int found;
  46. const char *key = luaL_checkstring(L, 2);
  47. luaR_result res = luaR_findkey(ptable, key, LUAR_FINDFUNCTION, &found);
  48. if (found)
  49. lua_pushlightfunction(L, (void*)(size_t)res);
  50. else
  51. lua_pushnil(L);
  52. return 1;
  53. }
  54. luaR_result luaR_findentry(void *data, const char *key, lu_byte *ptype) {
  55. int found;
  56. unsigned idx = (unsigned)data - 1;
  57. luaR_result res;
  58. *ptype = LUA_TNIL;
  59. /* First look at the functions */
  60. res = luaR_findkey(lua_rotable[idx].pfuncs, key, LUAR_FINDFUNCTION, &found);
  61. if (found) {
  62. *ptype = LUA_TLIGHTFUNCTION;
  63. return res;
  64. } else {
  65. /* Then at the values */
  66. res = luaR_findkey(lua_rotable[idx].pvalues, key, LUAR_FINDVALUE, &found);
  67. if(found) {
  68. *ptype = LUA_TNUMBER;
  69. return res;
  70. }
  71. }
  72. return 0;
  73. }