Access Lua script variables through Lua API in simple C

Source: Internet
Author: User

1. Introduction
This section describes some Lua APIs for Stack operations and data type determination. You can use these functions to obtain the variable values in the script.

2. Steps
Compile the test01.lua script, create the console C ++ program in vs2003, correctly configure the program, run the result, modify the script test02.lua, and view the execution result.

3. Test script
The following is the Lua script for testing.

Function plustwo (X)
Local A = 2;
Return x +;
End;
Rows = 6;
Cols = plustwo (rows );

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

4. Console Program
# 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] 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;
}

Related Article

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.