Virus721
Virus721

Reputation: 8315

Lua - C API - Create variables before running

I would like to extend the Lua so that when a user writes a script, a variable is already available to him. This variable should be an instance of a custom class.

For that I'm doing lua_newuserdata and lua_setglobal( L, "variableName" ); on the Lua stack before running the script.

Them problem is that it is crashing, so I'm not sure if it is crashing because I'm attempting to create object instances before running the script or because I have another error somewhere else.

Is it allowed to create object instances before running a LUA script ? And if not, what other way do I have to create a variable that is initially present in the globals without the user havingto do anything to retreive it ?

Thank you.

Upvotes: 0

Views: 995

Answers (1)

Nick Gammon
Nick Gammon

Reputation: 1171

I would like to extend the Lua so that when a user writes a script, a variable is already available to him.

That is certainly possible. Once the Lua state exists you can create global variables (ie. place key/value pairs in the global environment table).

Is it allowed to create object instances before running a LUA script ?

Yes it is. In my code I preload all sorts of stuff. Tables of useful things for the end-user. Extra libraries they can call.

Example code:

typedef struct { const char* key; int val; } flags_pair;
...
static flags_pair trigger_flags[] =
{
  { "Enabled", 1 },  // enable trigger 
  { "OmitFromLog", 2 },  // omit from log file 
  { "OmitFromOutput", 4 },  // omit trigger from output 
  { "KeepEvaluating", 8 },  // keep evaluating 
  { "IgnoreCase", 16 },  // ignore case when matching 
  { "RegularExpression", 32 },  // trigger uses regular expression 
  { "ExpandVariables", 512 },  // expand variables like @direction 
  { "Replace", 1024 },  // replace existing trigger of same name 
  { "LowercaseWildcard", 2048 },   // wildcards forced to lower-case
  { "Temporary", 16384 },  // temporary - do not save to world file 
  { "OneShot", 32768 },  // if set, trigger only fires once 
  { NULL, 0 }
};
...
static int MakeFlagsTable (lua_State *L, 
                           const char *name,
                           const flags_pair *arr)
{
  const flags_pair *p;
  lua_newtable(L);
  for(p=arr; p->key != NULL; p++) {
    lua_pushstring(L, p->key);
    lua_pushnumber(L, p->val);
    lua_rawset(L, -3);
  }
  lua_setglobal (L, name);
  return 1;
}
...
  MakeFlagsTable (L, "trigger_flag", trigger_flags)

Upvotes: 2

Related Questions