一个简单的Lua解释器


#include "stdafx.h"



#include<stdarg.h>

#include<stdlib.h>

#include<stdio.h>

#include<string.h>    

#include<math.h>



#include<errno.h>

extern "C"{

#include "lua.h"

#include "lauxlib.h"

#include "lualib.h"

}



lua_State *L;



void errormethod(const char *fmt, ...){

	va_list argp;

	va_start(argp, fmt);

	vfprintf(stderr, fmt, argp);

	va_end(argp);

	lua_close(L);

	//exit(EXIT_FAILURE);

}



static int l_sin(lua_State* L){

	//double d = lua_tonumber(L, 1);

	double d = luaL_checknumber(L, 1);

	lua_pushnumber(L, sin(d));

	//printf("call1 %f\n", d);

	return 1;

} 



static int add(lua_State* L){

	int n1 = lua_tonumber(L, 1);

	int n2 = lua_tonumber(L, 2);

	int sum = n1 + n2;

	lua_pushnumber(L, sum);

	//printf("call2 %f\n", d);  

	return 1;

} 

  

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

{

	char buff[256];

	int error;

	L = luaL_newstate();//创建Lua环境

	luaL_openlibs(L);//加载标准库

	lua_pushcfunction(L, l_sin);

	lua_setglobal(L, "mysin");

	lua_pushcfunction(L, add);

	lua_setglobal(L, "add");

		

	while(fgets(buff, sizeof(buff), stdin) != NULL){

		error = luaL_loadbuffer(L, buff, strlen(buff), "line") || lua_pcall(L, 0, 0, 0);

		if(error){  

			//errormethod("%s\n", lua_tostring(L, -1));

			fprintf(stderr, "%s\n", lua_tostring(L, -1));

			lua_pop(L, -1);

		}

  

	}

//	lua_close(L);

	system("pause");

	return 0;

}

From Lua程序设计..

给我的认识是

Lua仅仅是一门嵌入式的脚本语言

需要宿主语言去启动它。

 

你可能感兴趣的:(lua)