C + + Call Lua Simple example

Source: Internet
Author: User

First of all configure the environment, Baidu Library this talk in detail

Http://wenku.baidu.com/view/7912da3667ec102de2bd8957.html

After the environment was configured, I also wrote a simple call

Main.cpp

#include <stdio.h>

extern "C" {

#include "Lua.h"

#include "Lualib.h"

#include "Lauxlib.h"

};

Lua_state *l;

int luaadd (int x, int y)

{

int sum;

Lua_getglobal (L, "add");

Lua_pushnumber (L, x);

Lua_pushnumber (L, y);

Lua_call (L, 2, 1);

sum = (int) lua_tonumber (L,-1);

Lua_pop (L, 1);

return sum;

}

int main (int argc, char *argv[])

{

int sum = 0;

L = Lua_open ();

Luaopen_base (L);

Lual_openlibs (L);

Lual_loadfile (L, "Add.lua");

Lua_pcall (L, 0, Lua_multret, 0);

sum = Luaadd (10, 15);

printf ("The sum is%d\n", sum);

Lua_close (L);

return 0;

}

Add.lua

1--simple example, only do integer addition

2 function Add (x, y)

3 return x + y

4 End

When there is no problem after compiling, there are some problems with the execution, as follows:

Panic:unprotected error in call to Lua APIs (attempt to call a nil value)

Results Google a bit, said is Lual_loadfile replaced Lual_dofile, at that time I used is lual_dofile, this is a possible reason, but not mine.

Finally found the reason, Add.lua placed in the wrong place, I put it in the VS. cpp files in the same directory, and then put into the engineering directory inside.

Available Luaide Downloads: http://www.blueantstudio.net/content/index_static.php

Note: Content reproduced from: http://www.cnblogs.com/good90/archive/2012/08/19/2645997.html

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.