Apply Lua in your game: call function

xiaoxiao2021-03-06  40

Suppose you define a function in the script:

Function main (Number) Number = Number 1 Return Numbend

In your game code, you want to call this function at some point to get its return value.

In Lua, the function is equivalent to variables, so you can get this function like this:

Lua_GETGLOBAL (L, "main"); // Function Now Stack Top

Now, we can call this function and pass it to its correct parameters:

Lua_PushNumber (L, 100); // Put the parameter stack Lua_PCALL (L, 1, 1, 0); // Call the function, there is a parameter, a return value // Return value Now stack top int result = Lua_tonumber (L, -1);

Result is the return value of the function

The complete test code is as follows:

#include "lua.h" #include "lauxlib.h" #include "lualib.h"

INT Main (int Argc, char * argv []) {Lua_State * L = Lua_Open (); LuaOpen_Base (L);

Const char * buf = "function main (number) Number = Number 1 Return Number End

Lua_Dostring (BUF);

Lua_GETGLOBAL (LUA_PUSHNUMBER (LUA_PUSHNUMBER (LUA_PUSHNUMBER (LUA_PCALL (L, 1, 1, 0);

Int results = Lua_tonumber (L, -1);

Assert (result == 101);

Lua_Close (L);

Return 0;}

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

New Post(0)