Applying Lua in your game (3): use lua in CPP

xiaoxiao2021-03-06  46

LUA and host program exchange parameters are made through a runtime stack, and the information of the runtime stack is placed in a structure of a Lua_State, and the API provided by Lua requires a Lua_State * pointer, except for one:

Lua_open ();

This function will return a Lua_State * type pointer. In your game code, you can have such a pointer, or there are multiple such a pointer.

Finally, you need to release this pointer, pass the function:

Lua_Close (L);

Pay attention to this fact, Open () and close () in your host program are always pairs, in C , if there are some things to appear, this usually means that you need a constructor and one Destructor, so we first make a package on Lua_State:

#ifndef Lua_extralibs # define Lua_extralibs / * Empty * / # ENDIF

Static const lual_reg lualibs [] = {{"base", Luaopen_Base}, {"Table", Luaopen_Table}, {"IO", LuaOpen_IO}, {"String", Luaopen_String}, {"Math", Luaopen_Math}, {" Debug ", Luaopen_Debug}, {" loadinglib ", Luaopen_loadLib}, / * add your libraries here * / Lua_extralibs {null, null}};

This is some of Lua to provide some auxiliary lib users. When using Lua_State, you can choose to turn it on or off.

The complete class is as follows:

// Lua_StateClass State {public: state (bool bopenstdlib = false): err_fn (0) {l = Lua_Open (); assert (L);

IF (BopenSTDLIB) {Open_STDLIB ();}} ~ state () {Lua_SETGCTHRESHOLD (LUA_SETGCTHRESHOLD (LUA_CLOSE (L);} void Open_STDLIB () {Assert (L); const lual_reg * lib = lualibs; -> Func; lib ) {lib-> func (l); / * open library * / lua_settop (l, 0); / * discard any results * /}} Lua_State * get_handle () {Return L;}

INT Error_fn () {Return Err_fn;} private: Lua_State * L;

Int err_fn;};

Usually we only use a Lua_State * pointer in the game code, so we implements a single piece for it, and the default opens all Lua supplied LIB:

// Return The Global Instancestate * Lua_State () {Static State L (TRUE);

Return & l;

转载请注明原文地址:https://www.9cbs.com/read-68756.html

New Post(0)