SoFunction
Updated on 2025-03-10

Simple example of accessing LUA script variables through LUA API in C language

1. Introduction

This section introduces some LUA APIs about stack operations and data type judgment. You can use these functions to obtain variable values ​​in scripts.

2. Steps

Write a script, create a console C++ program in VS2003 and configure it correctly, execute the viewing result, and view the execution result after modifying the script

3. Test script

The following is the lua script used to test

Copy the codeThe code is as follows:

function plustwo(x)   
      local a = 2;   
      return x+a;
end;
rows = 6;
cols = plustwo(rows);

The above script defines one function and two global variables (LUA script variables are global by default). In the subsequent C++ program, we will obtain these two variables rows, cols through stack operations.

4.Console Programs

Copy the codeThe code is as follows:

#include <iostream>

extern "C"
{
    #include ""
    #include ""
    #include ""
}

using namespace std;

int main(int argc, char* argv[])
{
    cout << "01_Read_Stack" << endl;

    /**//* Create a LUA VMachine */
    lua_State *L = lua_open();
    luaopen_base(L);
    luaopen_table(L);
    luaL_openlibs(L);
    luaopen_string(L);
    luaopen_math(L);

    int iError;
    iError = luaL_loadfile(L, "../");
    if (iError)
    {
        cout << "Load script FAILED!" << lua_tostring(L, -1)<< endl;
        lua_close(L);
        return 1;
    }
    iError = lua_pcall(L, 0, 0, 0);
    if (iError)
    {
        cout << "pcall FAILED"<< lua_tostring(L, -1)<< iError<< endl;
        lua_close(L);
        return 1;
    }
   
    lua_getglobal(L, "rows");
    lua_getglobal(L, "cols");

    if (!lua_isnumber(L, -2))
   {
        cout << "[rows] is not a number" << endl;
        lua_close(L);
        return 1;
    }
    if (!lua_isnumber(L, -1))
    {
        cout << "[cols] is not a number" << endl;
        lua_close(L);
        return 1;
    }
    cout << "[rows]"
         << static_cast<int> (lua_tonumber(L, -2))
         << "[cols]"
         << static_cast<int> (lua_tonumber(L, -1))
         << endl;

    lua_pop(L,2);
    lua_close(L);
    return 0;
}