您的位置:首页 > 编程语言 > Lua

lua脚本demo实例

2016-06-27 11:41 483 查看
-- account.lua
-- from PiL 1, Chapter 16

Account = {balance = 0}

function Account:new (o, name)
o = o or {name=name}
setmetatable(o, self)
self.__index = self
return o
end

function Account:deposit (v)
self.balance = self.balance + v
end

function Account:withdraw (v)
if v > self.balance then error("insufficient funds on account "..self.name) end
self.balance = self.balance - v
end

function Account:show (title)
print(title or "", self.name, self.balance)
end

--面向对象编程?类与对象的使用?
a = Account:new(nil,"demo")
a:show("after creation")
a:deposit(1000.00)
a:show("after deposit")
a:withdraw(100.00)
a:show("after withdraw")

-- this would raise an error
--[[
b = Account:new(nil,"DEMO")
b:withdraw(100.00)
--]]

array = {"Lua", "Tutorial","java","lua"}

len=table.getn(array)

print(len)
print(#array)

for i= 0, len do
print(array[i])
end

--多维数组

-- Initializing the array
array = {}
for i=1,3 do
array[i] = {}
for j=1,3 do
array[i][j] = i*j
end
end

-- Accessing the array
for i=1,3 do
for j=1,3 do
print(array[i][j])
end
end

--迭代器
array = {"Lua", "Tutorial"}

for key,value in ipairs(array)
do
print(key.."="..value)
end

--排序表格
print ("排序表格")
fruits = {"banana","orange","apple","grapes"}
for k,v in ipairs(fruits) do
print(k,v)
end
table.sort(fruits)
print("sorted table")
for k,v in ipairs(fruits) do
print(k,v)
end

-- bisect.lua
-- bisection method for solving non-linear equations

delta=1e-6	-- tolerance

function bisect(f,a,b,fa,fb)
local c=(a+b)/2
io.write(n," c=",c," a=",a," b=",b,"\n")
if c==a or c==b or math.abs(a-b)<delta then return c,b-a end
n=n+1
local fc=f(c)
if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end
end

-- find root of f in the inverval [a,b]. needs f(a)*f(b)<0
function solve(f,a,b)
n=0
local z,e=bisect(f,a,b,f(a),f(b))
io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z)))
end

-- our function
function f(x)
return x*x*x-x-1
end

-- find zero in [1,2]
solve(f,1,2)

--coroutine 协同程序 多线程?

co = coroutine.create(function (value1,value2)
local tempvar3 =10
print("coroutine section 1", value1, value2, tempvar3)
local tempvar1 = coroutine.yield(value1+1,value2+1)
tempvar3 = tempvar3 + value1
print("coroutine section 2",tempvar1 ,tempvar2, tempvar3)
local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2)
tempvar3 = tempvar3 + value1
print("coroutine section 3",tempvar1,tempvar2, tempvar3)
return value2, "end"
end)

print("main", coroutine.resume(co, 3, 2))
print("main", coroutine.resume(co, 12,14))
print("main", coroutine.resume(co, 5, 6))
print("main", coroutine.resume(co, 10, 20))

function getNumber()
local function getNumberHelper()
co = coroutine.create(function ()
coroutine.yield(1)
coroutine.yield(2)
coroutine.yield(3)
coroutine.yield(4)
coroutine.yield(5)
end)
return co
end
if(numberHelper) then
status, number = coroutine.resume(numberHelper);
if coroutine.status(numberHelper) == "dead" then
numberHelper = getNumberHelper()
status, number = coroutine.resume(numberHelper);
end
return number
else
numberHelper = getNumberHelper()
status, number = coroutine.resume(numberHelper);
return number
end
end

for index = 1, 10 do
print(index, getNumber())
end
--http://www.yiibai.com/lua/lua_debugging.html

function myfunction ()
print(debug.traceback("Stack trace"))
print(debug.getinfo(1))
print("Stack trace end")
return 10
end
myfunction ()
print(debug.getinfo(1))
function currDir()
os.execute("cd > cd.tmp")
local f = io.open("cd.tmp", r)
local cwd = f:read("*a")
f:close()
os.remove("cd.tmp")
return cwd
end

--注意当前路径
dir = currDir()
print (dir)

--- 当前文件名
local __FILE__ = debug.getinfo(1,'S').source:sub(2)
print(__FILE__)

--window
obj=io.popen("cd")  --如果不在交互模式下,前面可以添加local
path=obj:read("*all"):sub(1,-2)    --path存放当前路径
obj:close()   --关掉句柄
--拼凑字符串demo
print("path="..path);
print(string.format("path=%s",path));

os.execute("ping www.baidu.com")

--http://www.yiibai.com/lua/lua_file_io.html

-- Opens a file in read
file = io.open("main.lua", "r")

-- sets the default input file as test.lua
io.input(file)

-- prints the first line of the file
print(io.read())

-- closes the open file
io.close(file)

-- Opens a file in append mode
file = io.open("test.lua", "a")

-- sets the default output file as test.lua
io.output(file)

-- appends a word test to the last line of the file
io.write("-- End of the test.lua file")

-- closes the open file
io.close(file)

-- Opens a file in read
file = io.open("test.lua", "r")

file:seek("end",-25)
print(file:read("*a"))

-- closes the opened file
file:close()
function myfunction ()
n = n/nil
end

if pcall(myfunction) then
print("Success")
else
print("Failure")
end

function myfunction2 ()
n = n/nil
end

function myerrorhandler( err )
print( "myerrorhandler ERROR:"..err )
end

status = xpcall( myfunction2, myerrorhandler )
print( status)

--main.lua

print ("my lua")
io.write("Hello World,from ",_VERSION,"!\n")

-- globals.lua
-- show all global variables
local seen={}
function dump(t,i)
seen[t]=true
local s={}
local n=0
for k in pairs(t) do
n=n+1	s
=k
end
table.sort(s)
for k,v in ipairs(s) do
print(i,v)
v=t[v]
if type(v)=="table" and not seen[v] then
dump(v,i.."\t")
end
end

end

dump(_G,"")

local mymath =  {}

function mymath.add(a,b)
print(a+b)
end

function mymath.sub(a,b)
print(a-b)
end

function mymath.mul(a,b)
print(a*b)
end

function mymath.div(a,b)
print(a/b)
end

return mymath

module("mymath_old", package.seeall)

function mymath_old.add(a,b)
print(a+b)
end

function mymath_old.sub(a,b)
print(a-b)
end

function mymath_old.mul(a,b)
print(a*b)
end

function mymath_old.div(a,b)
print(a/b)
end

--http://www.yiibai.com/lua/lua_object_oriented.html

-- Meta class
Shape = {area = 0}
-- Base class method new
function Shape:new (o,side)
o = o or {}
setmetatable(o, self)
self.__index = self
side = side or 0
self.area = side*side;
return o
end
-- Base class method printArea
function Shape:printArea ()
print("The area is ",self.area)
end

-- Creating an object
myshape = Shape:new(nil,10)
myshape:printArea()

--继承
Square = Shape:new()
-- Derived class method new
function Square:new (o,side)
o = o or Shape:new(o,side)
setmetatable(o, self)
self.__index = self
return o
end

-- Derived class method printArea
function Square:printArea ()
print("The area of square is ",self.area)
end

-- Creating an object
mysquare = Square:new(nil,10)
mysquare:printArea()

Rectangle = Shape:new()
-- Derived class method new
function Rectangle:new (o,length,breadth)
o = o or Shape:new(o)
setmetatable(o, self)
self.__index = self
self.area = length * breadth
return o
end

-- Derived class method printArea
function Rectangle:printArea ()
print("The area of Rectangle is ",self.area)
end

-- Creating an object
myrectangle = Rectangle:new(nil,10,20)
myrectangle:printArea()

print(myrectangle.length)
print(myrectangle.area)
--http://www.yiibai.com/lua/lua_modules.html

mymathmodule = require("mymath")
mymathmodule.add(10,20)
mymathmodule.sub(30,20)
mymathmodule.mul(10,20)
mymathmodule.div(30,20)

print("=======================")
mymathmodule = require("mymath_old")
mymathmodule.add(10,20)
mymathmodule.sub(30,20)
mymathmodule.mul(10,20)
mymathmodule.div(30,20)

local seen={}

print (type(seen))

print(type("What is my type"))   --> string
t=10
print(type(5.8*t))               --> number
print(type(true))                --> boolean
print(type(print))               --> function
print(type(type))                --> function
print(type(nil))                 --> nil
print(type(type(ABC)))           --> string

for i=10,1,-1
do
print(i)
end

--http://blog.csdn.net/zhangxaochen/article/details/8095007

--math.randomseed(os.time())

--math.randomseed(tostring(os.time()):reverse():sub(1, 6))

math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6)))

while( true )
do
print("This loop will run forever.")
line=math.random(0,10)
print(line)
if line==2 then
break
end

end
图片下载:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: