您的位置:首页 > 科技 > IT业 > Linux系统安装Lua语言及Lua外部库

Linux系统安装Lua语言及Lua外部库

2024/7/6 21:05:12 来源:https://blog.csdn.net/m0_73500130/article/details/139928186  浏览:    关键词:Linux系统安装Lua语言及Lua外部库

安装Lua 

 Lua语言是一种轻量级、高效且可扩展的脚本语言,具有简洁易学的语法和占用资源少的特点。它支持动态类型,提供了丰富的表达式和运算符,同时具备自动垃圾回收机制和跨平台性。Lua语言易于嵌入到其他应用程序中,并可与其他语言进行交互,因此在游戏开发、移动应用开发、嵌入式系统和网络服务等领域有着广泛的应用。

lua语言官方网站: The Programming Language Lua

在Linux系统安装Lua语言非常简洁,先更新软件列表:

sudo apt update

 安装Lua语言:

sudo apt install lua5.4

安装Lua语言开发相关的资源包,有了它以后开发者可以编写C/C++代码来扩展Lua的功能,实现一些在Lua脚本中难以实现或者效率较低的操作。

sudo apt-get install liblua5.4-dev

 验证下是否安装成功:

lua -v

 安装Lua包管理器luarocks(在/home家目录)

wget https://luarocks.org/releases/luarocks-3.11.1.tar.gz

解压压缩包 

tar zxpf luarocks-3.11.1.tar.gz

 安装相关配置

 ./configure && make && sudo make install

 在终端输入:

 lua

 经典的hello world

print("hello world")

在终端输入命令即可运行lua脚本:

lua hello.lua

安装外部的Lua库并搭建一个Web服务器

 Lua有时会用到luasql库操作数据库(目前是支持lua5.3),还有使用lua来编写Nginx服务器脚本,我这里是构建了一个简单的Web服务器:

使用luarocks安装lua的网络套接字库luasocket

sudo luarocks install luasocket

在Lua的交互页面输入命令即可导入luasocket包: 

require("socket")

 编写脚本并引入luasocket库,开启8080端口

local socket = require("socket")  
local server = socket.bind("*", 8080)  
local ip, port = server:getsockname()  print("ip地址", ip, "端口", port)  while true do  local client = server:accept()  client:settimeout(0)  local line, err = client:receive()  if not err then  print("Received line: ", line)  local response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nGay Away!!!!"  client:send(response)  end  client:close()  
end

运行成功后在浏览器输入    虚拟机或服务器的ip地址:8080   即可看到我们想输出的信息 

构建一个可以打开HTML文件的Web服务器

local socket = require("socket")  
local server = socket.bind("*", 8080)  
local ip, port = server:getsockname()  
local fs = require("io")  -- 用于文件操作  print("服务器监听在 ip地址 ", ip, " 端口 ", port)  while true do  local client = server:accept()  client:settimeout(0)  local line, err = client:receive()  if not err then  print("Received line: ", line)  -- 读取index.html文件的内容  local file, err = fs.open("index.html", "r")  if not err then  local content = file:read("*a") -- 读取文件所有内容  file:close()  -- 构造HTTP响应  local response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" .. content  client:send(response)  else  print("Error opening file: ", err)  local response = "HTTP/1.1 500 Internal Server Error\r\n\r\nError opening index.html"  client:send(response)  end  end  client:close()  
end

 运行成功:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com