lua--从白开始(2)

眼下lua最新的版本号,5.2.3。

这个例子是一个简单lua分析器,来源自《Lua游戏开发实践指南》。

测试程序的功能:解决简单lua说明,例如:print("Hello world!");

function fun(x ,y) return x + y end

z =fun(1,1);

print(z);

结果例如以下图:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc2VuX2Jsb2c=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >

源代码例如以下:

simple_main.cpp:

#include <stdio.h>
#include <string.h>
#include "cLua.h"

LuaGlue _Version(lua_State *L)
{
	puts("This is 2.o fuck you!");
	return 0;
}

char gpCommandBuffer[254];

const char* GetCommand()
{
	memset(gpCommandBuffer,0,sizeof(gpCommandBuffer));
	printf("Read>");
	fgets(gpCommandBuffer,254,stdin);
	//printf("&&&&%s&&&&&",gpCommandBuffer);
	gpCommandBuffer[strlen(gpCommandBuffer) - 1] = 0;
	//printf("-----%s----",gpCommandBuffer);
	return gpCommandBuffer;
}

int main()
{
	puts("SKLDB");
	puts("fky");

	cLua *pLua = new cLua;

	pLua->AddFunction("Version",_Version);

	const char *pCommand = GetCommand();

	while (strcmp(pCommand,"QUIT") != 0)
	{
		if (! pLua->RunString(pCommand))
		{
			printf("Error is:%s",pLua->GetErrorString());
		}
		pCommand = GetCommand();
	}

	delete pLua;

	return 0;
}

cLua.h:

#ifndef __CLUA__
#define __CLUA__

struct lua_State;

#define LuaGlue extern "C" int
extern "C" {
typedef int (*LuaFunctionType)(struct lua_State *pLuaState);
};

class cLua
{
public:
	cLua();
	virtual ~cLua();

	bool		RunScript(const char *pFilename);
	bool		RunString(const char *pCommand);
	const char *GetErrorString(void);
	bool		AddFunction(const char *pFunctionName, LuaFunctionType pFunction);
	const char *GetStringArgument(int num, const char *pDefault=NULL);
	double		GetNumberArgument(int num, double dDefault=0.0);
	void		PushString(const char *pString);
	void		PushNumber(double value);

	void		SetErrorHandler(void(*pErrHandler)(const char *pError)) {m_pErrorHandler = pErrHandler;}

	lua_State	*GetScriptContext(void)		{return m_pScriptContext;}

private:
	lua_State	*m_pScriptContext;
	void(*m_pErrorHandler)(const char *pError);
};

#endif

cLua.cpp:

#include <stdio.h>
#include <string.h>
#include <string>

#include "cLua.h"
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}

cLua::cLua()
{
	m_pErrorHandler = NULL;

	m_pScriptContext = luaL_newstate();
	luaL_openlibs(m_pScriptContext);
	//luaopen_base(m_pScriptContext);
	//luaopen_io(m_pScriptContext);
	//luaopen_string(m_pScriptContext);
	//luaopen_math(m_pScriptContext);
	//luaopen_debug(m_pScriptContext);
	//luaopen_table(m_pScriptContext);
}

cLua::~cLua()
{
	if(m_pScriptContext)
		lua_close(m_pScriptContext);
}

static std::string findScript(const char *pFname)
{
	FILE *fTest;

	char drive[_MAX_DRIVE];
	char dir[_MAX_DIR];
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];

	_splitpath( pFname, drive, dir, fname, ext );

	std::string strTestFile = (std::string) drive + dir + "Scripts\\" + fname + ".LUB";
	fTest = fopen(strTestFile.c_str(), "r");
	if(fTest == NULL)
	{
		//not that one...
		strTestFile = (std::string) drive + dir + "Scripts\\" + fname + ".LUA";
		fTest = fopen(strTestFile.c_str(), "r");
	}

	if(fTest == NULL)
	{
		//not that one...
		strTestFile = (std::string) drive + dir + fname + ".LUB";
		fTest = fopen(strTestFile.c_str(), "r");
	}

	if(fTest == NULL)
	{
		//not that one...
		//not that one...
		strTestFile = (std::string) drive + dir + fname + ".LUA";
		fTest = fopen(strTestFile.c_str(), "r");
	}

	if(fTest != NULL)
	{
		fclose(fTest);
	}

	return strTestFile;
}

bool cLua::RunScript(const char *pFname)
{
	std::string strFilename = findScript(pFname);
	const char *pFilename = strFilename.c_str();

	if (0 != luaL_loadfile(m_pScriptContext, pFilename))
	{
		if(m_pErrorHandler)
		{
			char buf[256];
			sprintf(buf, "Lua Error - Script Load\nScript Name:%s\nError Message:%s\n", pFilename, luaL_checkstring(m_pScriptContext, -1));
			m_pErrorHandler(buf);
		}

		return false;
	}
	if (0 != lua_pcall(m_pScriptContext, 0, LUA_MULTRET, 0))
	{
		if(m_pErrorHandler)
		{
			char buf[256];
			sprintf(buf, "Lua Error - Script Run\nScript Name:%s\nError Message:%s\n", pFilename, luaL_checkstring(m_pScriptContext, -1));
			m_pErrorHandler(buf);
		}

		return false;
	}
	return true;

}

bool cLua::RunString(const char *pCommand)
{
	if (0 != luaL_loadbuffer(m_pScriptContext, pCommand, strlen(pCommand), NULL))
	{
		if(m_pErrorHandler)
		{
			char buf[256];
			sprintf(buf, "Lua Error - String Load\nString:%s\nError Message:%s\n", pCommand, luaL_checkstring(m_pScriptContext, -1));
			m_pErrorHandler(buf);
		}

		return false;
	}
	if (0 != lua_pcall(m_pScriptContext, 0, LUA_MULTRET, 0))
	{
		if(m_pErrorHandler)
		{
			char buf[256];
			sprintf(buf, "Lua Error - String Run\nString:%s\nError Message:%s\n", pCommand, luaL_checkstring(m_pScriptContext, -1));
			m_pErrorHandler(buf);
		}

		return false;
	}
	return true;
}

const char *cLua::GetErrorString(void)
{
	return luaL_checkstring(m_pScriptContext, -1);
}

bool cLua::AddFunction(const char *pFunctionName, LuaFunctionType pFunction)
{
	lua_register(m_pScriptContext, pFunctionName, pFunction);
	return true;
}

const char *cLua::GetStringArgument(int num, const char *pDefault)
{
	return luaL_optstring(m_pScriptContext, num, pDefault);

}

double cLua::GetNumberArgument(int num, double dDefault)
{
	return luaL_optnumber(m_pScriptContext, num, dDefault);
}

void cLua::PushString(const char *pString)
{
	lua_pushstring(m_pScriptContext, pString);
}

void cLua::PushNumber(double value)
{
	lua_pushnumber(m_pScriptContext, value);
}

源代码链接:http://download.csdn.net/detail/shinhwalin/7831493

版权声明:本文博主原创文章,博客,未经同意不得转载。

时间: 2024-07-30 10:20:55

lua--从白开始(2)的相关文章

nginx+lua打造10K qps+的web应用

背景篇 由于项目流量越来越大,之前的nginx+php-fpm的架构已经难以承受峰值流量的冲击,春节期间集群负载一度长时间维持0%的idle,于是这段时间逐渐对旧系统进行重构. 受高人指点,发现lua这个好东西.因此在技术选型上,我们使用lua代替部分的php逻辑,比如请求的过滤.lua是一种可以嵌入nginx配置文件的动态语言,结合nginx的请求处理过程(参见另一篇博文),lua可以在这些阶段接管请求的处理. 我们的环境使用openresty搭建,openresty包括了很多nginx常用扩

Lua中调用 cocos2d-x 的滑动条/滚动条 ScrollView

 ScrollView 我想玩儿过手机的朋友对滑动条都不陌生吧,(旁边: 这不是废话么???? )   那好吧,废话不多说直接开始ScrollView吧 local m_BaseNode  -- 主场景 local CreateScroll    -- 房间分级滑动视图 local CreateStageNode   -- 创建节点 local m_ScrollView              -- 滑动层变量 local m_Inner     -- 内容器 local addScrol

使用Nginx+Lua(OpenResty)开发高性能Web应用

在互联网公司,Nginx可以说是标配组件,但是主要场景还是负载均衡.反向代理.代理缓存.限流等场景:而把Nginx作为一个Web容器使用的还不是那么广泛.Nginx的高性能是大家公认的,而Nginx开发主要是以C/C++模块的形式进行,整体学习和开发成本偏高:如果有一种简单的语言来实现Web应用的开发,那么Nginx绝对是把好的瑞士军刀:目前Nginx团队也开始意识到这个问题,开发了nginxScript:可以在Nginx中使用JavaScript进行动态配置一些变量和动态脚本执行:而目前市面上

【笨木头Lua专栏】基础补充02:函数的几个特别之处

没想到距离上一篇基础补充已经过了1年多了,近期准备捡回Lua,把基础都补补,今天来聊聊Lua的函数吧~ 0.环境 我突然对Lua又大感兴趣的最主要原因是,Cocos Code IDE開始浮出水面了,它是Cocos2d-x官方出的一款专门针对Cocos2d-x+Lua或JS的IDE.试着用了,尽管不能说非常完美.但,非常值得期待. 所以,本文使用的Lua编辑器就选它了,大家就任意吧~ 笨木头花心贡献,哈?花心?不.是用心~ 转载请注明,原文地址:http://www.benmutou.com/ar

Nginx+Lua(OpenResty)开发高性能Web应用

使用Nginx+Lua(OpenResty)开发高性能Web应用 博客分类: 跟我学Nginx+Lua开发 架构 ngx_luaopenresty 在互联网公司,Nginx可以说是标配组件,但是主要场景还是负载均衡.反向代理.代理缓存.限流等场景:而把Nginx作为一个Web容器使用的还不是那么广泛.Nginx的高性能是大家公认的,而Nginx开发主要是以C/C++模块的形式进行,整体学习和开发成本偏高:如果有一种简单的语言来实现Web应用的开发,那么Nginx绝对是把好的瑞士军刀:目前Ngin

nginx+lua实现简单的waf网页防火墙功能

Nginx+Lua实现WAF 参考地址:http://www.2cto.com/Article/201303/198425.html 2016年8月2日 安装LuaJIT http://luajit.org/download/LuaJIT-2.0.4.tar.gz tar xf LuaJIT-2.0.4.tar.gz cd LuaJIT-2.0.4 make && make install 即可 下载ngx_devel_kit https://codeload.github.com/sim

nginx + lua 构建网站防护waf(一)

最近在帮朋友维护一个站点.这个站点是一个Php网站.坑爹的是用IIS做代理.出了无数问题之后忍无可忍,于是要我帮他切换到nginx上面,前期被不断的扫描和CC.最后找到了waf这样一个解决方案缓解一下.话不多说直接开始. waf的作用: 防止sql注入,本地包含,部分溢出,fuzzing测试,xss,SSRF等web攻击 防止svn/备份之类文件泄漏 防止ApacheBench之类压力测试工具的攻击 屏蔽常见的扫描黑客工具,扫描器 屏蔽异常的网络请求 屏蔽图片附件类目录php执行权限 防止web

Lua和C++的通信流程代码实例

C++从Lua中获取一个全局变量的字符串. 1. 引入头文件 我们来看看要在C++中使用Lua,需要些什么东西 复制代码代码如下: /*    文件名:    HelloLua.h    描 述:    Lua Demo   创建人:    笨木头   创建日期:   2012.12.24 */ #ifndef __HELLO_LUA_H_#define __HELLO_LUA_H_ #include "cocos2d.h" extern "C" {#include

51CTO专访淘宝清无:漫谈Nginx服务器与Lua语言

http://os.51cto.com/art/201112/307610.htm 说到Web服务器,也许你第一时间会想到Apache,也许你会想到Nginx.虽然说Apache依然是Web服务器的老大,但是在全球前 1000大Web服务器当中,22.4%使用NGINX.这些服务器包括诸如Facebook.Hulu和WordPress之类的网络巨头使用的服务 器.在今年刚刚结束的O'Reilly Velocity China 2011会议上,51CTO编辑有幸采访到了目前就职淘宝的王晓哲.在<淘

Cocos2d-x Lua 读取Csv文件,更方便的使用数据

我的书上或者是我曾经出售的源码里,都有Csv文件的影子. 也许是先入为主吧,我工作那会用的最久的配置文件就是Csv,所以我在很多游戏里都会情不自禁地优先选择它. Csv文件,格式很简单,就是一行一条数据,字段之间用逗号分隔,策划也可以方便地使用Excel进行编辑. Csv格式的文件,解析起来也很简单,所以自己动手写写很快~(小若:我就喜欢拿来主义,你怎么着) 最近在用Lua写游戏,对于技能.怪物等配置,我还是选择用Csv~ 不得不说,Lua等脚本语言,在某些方面是C++没法比的,这次我就用Csv