如何在cc++工程中使lua

如何在cc++工程中使lua,第1张

ua和c

/

c++的数据交互通过栈进行,

*** 作数据时,首先将数据拷贝到"栈"上,然后获取数据,栈中的每个数据通过索引值进行定位,索引值为正时表示相对于栈底的偏移索引,索引值为负时表示相对于栈顶的偏移索引,索引值以1或

-

1为起始值,因此栈顶索引值永远为

-

1,

栈底索引值永远为1

"栈"相当于数据在lua和c

/

c++之间的中转地。每种数据都有相应的存取接口

[python]

view

plain

copy

--region

*.lua

--Date

--此文件由[BabeLua]插件自动生成

print("lua

script

func.lua

have

been

load

")

function

showinfo()

print("welcome

to

lua

world

")

end

function

showstr(str)

print("The

string

you

input

is

"

..

str)

end

function

add(x,y)

return

x+y

end

--endregion

[cpp]

view

plain

copy

#include

//lua头文件

#ifdef

__cplusplus

extern

"C"

{

#include

"lua.h"

#include

#include

}

#else

#include

#include

#include

#endif

int

main(int

argc,char

**

argv)

{

lua_State

*

L=NULL

/*

初始化

Lua

*/

L

=

lua_open()

/*

载入Lua基本库

*/

luaL_openlibs(L)

/*

运行脚本

*/

luaL_dofile(L,

"./script/func.lua")

//获取lua中的showinfo函数

lua_getglobal(L,"showinfo")

//cpp

调用无参数的lua函数,无返回值

lua_pcall(L,0,0,0)

//主动清理堆栈,也可以不调用

const

char

*

pstr="世界如此美好"

lua_getglobal(L,"showstr")

lua_pushstring(L,pstr)

//cpp

调用一个参数的的lua函数,无返回值

lua_pcall(L,1,0,0)

lua_getglobal(L,"add")

//参数从左到右压栈

lua_pushinteger(L,2)

lua_pushinteger(L,3)

lua_pcall(L,2,1,0)

printf("lua

add

function

return

val

is

%d

\n",lua_tointeger(L,-1))

/*

清除Lua

*/

lua_close(L)

return

1

}

#include <stdio.h>#include <lua.h>#include <lualib.h>#include <lauxlib.h> int echohello(){    printf("hello")    //return 1    return 0} int main(){    lua_State* ls = luaL_newstate()    luaL_openlibs(ls)    lua_pushcclosure(ls, echohello, 0)    lua_setglobal(ls, "echohello")    luaL_dostring(ls,         "print('start call c function...')\r\n"        "echohello()\r\n"        "print('')"        "print('end call c function...')\r\n"        )    lua_close(ls)    return 0}

我假设你知道如何设置lua编译环境,如何链接lua库

我假设你使用的是c语言,并且知道函数调用的内部原理(不知道的话请不要像我这样把echohello给pushcclosure进去)

gcc下是一样的。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/bake/11913018.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存