zoukankan      html  css  js  c++  java
  • 一个简单的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
    ", 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
    ", 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
    ", lua_tostring(L, -1));
    			fprintf(stderr, "%s
    ", lua_tostring(L, -1));
    			lua_pop(L, -1);
    		}
      
    	}
    //	lua_close(L);
    	system("pause");
    	return 0;
    }
    

    From Lua程序设计..

    给我的认识是

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

    需要宿主语言去启动它。

  • 相关阅读:
    黑马程序员简易聊天器笔记
    黑马程序员 最简单的浏览器
    Java 窗体布局
    黑马程序员交通系统
    黑马程序员–java 网络处理
    Swing入门级项目全程实录学习总结
    Swing入门级项目全程实录第7讲
    Swing入门级项目全程实录第3讲
    Swing入门级项目全程实录第2讲
    HTML基础教程
  • 原文地址:https://www.cnblogs.com/MyGameAndYOU/p/3958071.html
Copyright © 2011-2022 走看看