A simple example of a LUA script variable accessed through the LUA API in C language _lua

Source: Internet
Author: User
Tags lua

1. Introduction

This section describes some of the LUA APIs for stack operations, data type judgments, which you can use to get variable values in your scripts.

2. Steps

Write Test01.lua script, create a console C + + program in VS2003 and configure it correctly, perform view results, modify Test02.lua script and view execution results

3. Test scripts

Here is the Lua script for testing

Copy Code code as follows:

function Plustwo (x)
Local A = 2;
return x+a;
End
rows = 6;
cols = plustwo (rows);

The above script defines a function, two global variables (the LUA script variable is global by default). After the C + + program, we will get the two variables through the stack operation rows, cols.

4. Console Program

Copy Code code as follows:

#include <iostream>

extern "C"
{
#include "Lua.h"
#include "Lauxlib.h"
#include "Lualib.h"
}

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, "...). /test01.lua ");
    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] are 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.