Get the App
SLTechnology News&Howtos  ›  Development  › 

How to deal with the interactive callback function between C++ and lua

Shulou Source: shulou.com Published: 2022-06-03 02:24:07 10月02日 Update

This article mainly introduces how to deal with c++ and lua interactive callback function, has a certain reference value, interested friends can refer to, I hope you read this article after a lot of gains, the following let Xiaobian take you to understand.

1. Define the registration callback function in the header file, defined in the MyClass class

void register(unsigned short cmdID, LUA_FUNCTION func);//LUA_FUNCTION is actually an intvoid unregister();

2. Realization

void MyClass::register(unsigned short cmdID, LUA_FUNCTION func){m_luaFunction = func;//Callback function registered in lua (callback should be executed under certain conditions)LuaStack* stack = LuaEngine::getInstance()->getLuaStack();stack->pushInt(cmdID);stack->executeFunctionByHandler(func, 1);//1 represents number of parameters}void MyClass::unregister(){LuaEngine::getInstance()->removeScriptHandler(m_luaFunction); //Remove binding of lua function}

3. Use tolua++ to generate c++ code for use in lua interface

To modify MyClass_tolua.cpp as follows

1. Contains header files

#include "tolua_fix.h"

2, search register, because tolua++ regards LUA_FUNCTION as a type, so we need to make some modifications to this paragraph

(1)will

! tolua_isusertype(tolua_S,2,"LUA_FUNCTION",0,&tolua_err))

changed to

! lua_isfunction(tolua_S,2))

(2)will

LUA_FUNCTION callback = *((LUA_FUNCTION*) tolua_tousertype(tolua_S,3,0));

changed to

int callback = toluafix_ref_function(tolua_S, 3, 0);

4. Register callback function in lua file

local function operateResult(cmdID)cclog("%d", cmdID)endlocal Demo:onEnter()local myclass = MyClass:new()myclass:register(101,operateResult)end Thank you for reading this article carefully, I hope Xiaobian share "How to deal with c++ and lua interactive callback function" This article is helpful to everyone, but also hope that everyone will support, pay attention to industry information channels, more relevant knowledge waiting for you to learn!

Tags: Functions articles caches files number code code generation representatives values interests parameters and actually interfaces are in more friends conditions knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei macOS Apple Linux Docker