Home Backend Development PHP Tutorial Lua and C language call each other

Lua and C language call each other

Aug 08, 2016 am 09:23 AM
include lua printf quot

A lot of intermodulation between lua and c language appears in lua-nginx-module. Here are some test codes from Chapters 24-27 of "Lua Programming".

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdarg.h>
#include <stdlib.h>

#define MAX_COLOR 255

static void stackDump(lua_State *L);

static int l_split(lua_State *L)
{
	const char *s = luaL_checkstring(L, 1);
	const char *sep = luaL_checkstring(L, 2);
	const char *e;
	int i = 1;
	
	lua_newtable(L);
	
	while ((e = strchr(s, *sep)) != NULL)
	{
		lua_pushlstring(L, s, e-s);
		lua_rawseti(L, -2, i ++);
		s = e + 1;
	}
	
	lua_pushstring(L, s);
	lua_rawseti(L, -2, i);
	
	return 1;
}

int l_map(lua_State *L)
{
	int i, n;
	luaL_checktype(L, 1, LUA_TTABLE);
	luaL_checktype(L, 2, LUA_TFUNCTION);
	
	n = lua_objlen(L, 1);
	for (i = 1; i <= n; i ++)
	{
		//stackDump(L);
		//printf("=====1=====\n");
		lua_pushvalue(L, 2);
		//stackDump(L);
		//printf("=====2=====\n");
		lua_rawgeti(L, 1, i);
		//stackDump(L);
		//printf("=====3=====\n");
		lua_call(L, 1, 1);
		//stackDump(L);
		//printf("=====4=====\n");
		lua_rawseti(L, 1, i);
		//stackDump(L);
		//printf("=====5=====\n");
	}
	
	return 0;
}

// 通过Lua调用的c函数,通过打印栈说明每个函数有独立的栈
// 将c函数注册到lua中,从而被lua调用。
static int l_sin(lua_State *L)
{
	double d = lua_tonumber(L, 1);
	lua_pushnumber(L, sin(d));
	
	// stackDump(L);
	// printf("====l_sin===\n");
	
	return 1;
}

// c 调用lua 函数
// 从Lua中得到函数,在c语言中传入参数。
double f(lua_State *L,double x, double y)
{
	double z;
	lua_getglobal(L, "f");
	lua_pushnumber(L, x);
	lua_pushnumber(L, y);
	// table function 1.1 2.2 说明c语言调用Lua会共享相同的栈.
	// stackDump(L);
	// printf("=====f=====\n");
	
	if (lua_pcall(L, 2, 1, 0) != 0)
		printf("call f error\n");
	
	if (!lua_isnumber(L, -1))
		printf("function f must return a number\n");
	
	z = lua_tonumber(L, -1);
	lua_pop(L, 1);
	return z;
}

int getfield(lua_State *L, const char *key)
{
	int result;
	// stackDump(L);
	// printf("==1==\n");
	lua_getfield(L, -1, key);
	// stackDump(L);
	// printf("==2==\n");
	if (!lua_isnumber(L, -1))
		printf("invalid component\n");
	result = lua_tonumber(L, -1);
	lua_pop(L, 1);
	// stackDump(L);
	// printf("==4==\n");
	return result;
}

static void stackDump(lua_State *L)
{
	int i;
	int top = lua_gettop(L);
	for (i = 1; i <= top; ++ i)
	{
		int t = lua_type(L, i);
		switch(t) {
		case LUA_TSTRING:
			printf("'%s'", lua_tostring(L, i));
			break;
		case LUA_TBOOLEAN:
			printf(lua_toboolean(L, i) ? "true" : "false");
			break;
		case LUA_TNUMBER:
			printf("%g", lua_tonumber(L, i));
			break;
		default:
			printf("%s", lua_typename(L, t));
			break;
		}
		printf(" ");
	}
	printf("\n");
}

void load(lua_State *L, const char *fname, int *w, int *h) {
	if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0))
			printf("cannot run config.file\n");
	
	/*lua_getglobal(L, "height");
	lua_getglobal(L, "width");
	
	if (!lua_isnumber(L, -2))
		printf("width should be a number\n");
	
	if (!lua_isnumber(L, -1))
		printf("height should be a number\n");
	
	*w = lua_tointeger(L, -2);
	*h = lua_tointeger(L, -1);*/
	
	lua_getglobal(L, "table");
	
	if (!lua_istable(L, -1))
		printf("background should be table\n");
	
	printf("%f\n", f(L, 1.1, 2.2));
	
	float red = getfield(L, "r");
	float green = getfield(L, "g");
	float blue = getfield(L, "b");
	
	printf("%f, %f, %f\n", red, green, blue);
}

// lua 调用c代码可以模仿这里的格式
const char* testfunc = "t = mysplit(\"hi, hello\", \",\"); print(t[1], t[2])";

int main(void)
{
	char buff[256];
	int error;
	lua_State *L = luaL_newstate();
	luaL_openlibs(L);
	int w, h;
	// load(L, "test.lua", &w, &h);
	
	lua_pushcfunction(L, l_sin);
	lua_setglobal(L, "mysin");
	
	lua_pushcfunction(L, l_map);
	lua_setglobal(L, "mymap");
	
	lua_pushcfunction(L, l_split);
	lua_setglobal(L, "mysplit");
	
	if (luaL_dostring(L, testfunc))
		fprintf(stderr, "%s", lua_tostring(L, -1));
	
	/*
	while (fgets(buff, sizeof(buff), stdin) != NULL)
	{
		error = luaL_loadbuffer(L, buff, strlen(buff), "line");
		stackDump(L);
		error = error || lua_pcall(L, 0, 0, 0);
		stackDump(L);
	}
	
	if (error) {
		fprintf(stderr, "%s", lua_tostring(L, -1));
		lua_pop(L, 1);
	}*/
	
	lua_close(L);
	return 0;
}
Copy after login

test.lua

BULE = {r = 0, g = 0, b = 1}
table = {["r"] = 10, ["g"] = 23, ["b"] = 33}

function f(x, y)
	return x + y
end
Copy after login

Compile: gcc test.c -I/usr/local/include/luajit-2.0 -llua-5.1 -lm

The above introduces the mutual calling between Lua and C language, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install and configure Lua support for Nginx How to install and configure Lua support for Nginx Jun 02, 2023 pm 10:01 PM

Nginx installation and configuration Lua support By default, Nginx does not support Lua modules. You need to install the LuaJIT interpreter and recompile Nginx, or you can use the modules required by openrestry developed by Chinese people: LuaJIT, Ngx_devel and lua-nginx-module1. Environment preparation [root @nginx_lua~]#yuminstall-ygccgcc-c++makepcre-develzlib-developenssl-devel2. Download the latest luajit and ngx_devel_kit and lua-nginx-module decompression [r

How to integrate nginx with lua to operate mysql How to integrate nginx with lua to operate mysql May 16, 2023 pm 10:43 PM

The implementation idea is to directly configure the blacklist in nginx and implement it by writing logical blocks; write the filter in the server (Java) and unify the interceptors in the filter; write the interceptor in the server (Java) and unify the interceptors Interception; here are 3 implementation ideas. As for implementation solutions, there may be more, but if we think about it, writing logical blocks in nginx does not seem to be what many people are good at; it is not impossible to do it at the code level, but this is First, during peak business periods involving high concurrency, this will inevitably put greater pressure on back-end services. So are there any other better ways to deal with it? This is what lua is about, that is, nginx acts as a gateway and still acts as a proxy server, because nginx can integrate lua

Integration of Vue.js and Lua language to write lightweight embedded applications Integration of Vue.js and Lua language to write lightweight embedded applications Jul 31, 2023 pm 02:23 PM

The integration of Vue.js and Lua language to write lightweight embedded applications. In modern development, the front-end framework Vue.js and the scripting language Lua each have a wide range of applications. Vue.js is a progressive framework for building user interfaces, while Lua is a lightweight scripting language often used for embedded application and game development. This article will introduce how to integrate Vue.js with Lua language to write lightweight embedded applications, and provide code examples. First, we need to install Vue.j

What is the difference between php include and include_once What is the difference between php include and include_once Mar 22, 2023 am 10:38 AM

When we write web pages using PHP, sometimes we need to include code from other PHP files in the current PHP file. At this time, you can use the include or include_once function to implement file inclusion. So, what is the difference between include and include_once?

Integration of Vue.js and Lua language, best practices and experience sharing in building front-end engines for game development Integration of Vue.js and Lua language, best practices and experience sharing in building front-end engines for game development Aug 01, 2023 pm 08:14 PM

The integration of Vue.js and Lua language, best practices and experience sharing for building a front-end engine for game development Introduction: With the continuous development of game development, the choice of game front-end engine has become an important decision. Among these choices, the Vue.js framework and Lua language have become the focus of many developers. As a popular front-end framework, Vue.js has a rich ecosystem and convenient development methods, while the Lua language is widely used in game development because of its lightweight and efficient performance. This article will explore how to

How to use Redis+Lua script to implement the anti-swipe function of the counter interface How to use Redis+Lua script to implement the anti-swipe function of the counter interface May 28, 2023 pm 11:32 PM

[Implementation process] 1. Problem analysis If the set command is set, but when setting the expiration time, the setting is not successful due to network jitter and other reasons, then a dead counter (similar to a deadlock) will appear; 2. Solution Redis+Lua It is a good solution. Use a script to make the set command and the expire command work together so that Redis is executed without being interfered with. This guarantees atomic operations to a large extent. Why is it said that it guarantees atomic operations to a large extent rather than completely? ensure? Because problems may occur when Redis is executed internally, but the probability is very small; even for small-probability events, there are corresponding solutions, such as solving deadlocks. An idea worth referring to: To prevent deadlocks, the value of the lock will be stored in

How to use Lua script in Java ecosystem/Redis How to use Lua script in Java ecosystem/Redis Jun 02, 2023 pm 10:41 PM

1. Install LUA Installing LUA on Mac is very simple. Just use brew related commands directly; brewinstalllua uses the lua-v command to see that lua has been installed. 1) Simple use to create a test.lua file, the content is: Execute command: luatest.lua output is: 2. Introduction to lua syntax Lua provides interactive programming and scripted programming: Interactive programming: directly enter the syntax on the command line , you can execute it immediately and see the execution effect. Scripting is programming: write a script file and then execute it. 1. Comment Lua provides two comment methods: single-line comments and multi-line comments 1) Single-line comments use two minus signs;--2) Multi-line comments--[[Multi-line comments multi-line

How idaPro analyzes app decryption lua script How idaPro analyzes app decryption lua script May 18, 2023 am 08:34 AM

Through the previous idaPro debugging or hook, we can obtain the xxtea decryption key. For sign, we can directly open the original file: we can see the sign value: byds. Therefore, we can try to decrypt it with the xxtea decryption tool (which can be compiled from the source code on GitHub): Taking index.luac as an example, we see the changes before and after decryption of index.luac: We see that the lua script after decryption by xxtea is still not Plain text! We previously determined that the xxtea encryption was used based on the cocos2d framework source code and the master apk decoding result, and the Lua script of the app also has a signature value, which also confirms that it is the xxtea encryption method, but we

See all articles