• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

【lua】lua练手基础

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

lua的库文件地址: http://luaforge.net/projects/
lua官网 http://lua.org

--[[
print string.
multiple line comments.
like {} in Tcl.
]]--
print ("hello")
-- comments of this file.

-- variables
num = 1
str = "abc"
tab = {}
d = print

-- print type the variables.
print (type(num))
print (type(str))
print (type(tab))
print (type(d))

-- print global variables names.
print ("This lua version is:",_VERSION)


-- strings example.
lineStr = "single 'quoted' string and double \"quoted\" string inside."
print (lineStr)
lineStr2 = 'single \'quoted\' string and double "quoted" string inside.'
print (lineStr2)
mutipleLine = [[
mutiple line 1
with 'single' line
and "double" quoted strings inside.
]]
print(mutipleLine)


-- muliple assignments are valid.
a,b,c,d,e = 1, 2, 'three', "four", 5.501
print (a,b,c,d,e)

-- swap two variables
print(a, b)
a, b = b, a
print(a, b)

-- two dots (..) are used to concatenate strings.
print("a="..a.."\n",
"b="..b.."\n",
c.." c add d is:"..d.."\n",
e.." e add d is:"..d.."\n",
d.." d add e is:"..e.."\n")

-- io.write writes to stdout but without new line.
io.write("io.write".."without new line.")
-- print '\n'
print()


------------------------------table structure--------------------------
-- table is like array in C.
taba = {}
tabb = {1,2,3.3,"four"}
tabc = {"a", "b", "c", 4, 5.5}
-- print table this pointer.
print(taba, tabb, tabc)
-- print value in table with index id.
print(taba[0], tabb[1], tabc[2])

i = 1
while i < 6 do
io.write(tabc[i].."\n")
i = i + 1
end

-- table with string index.
addr = {}
addr.street = "shunyi"
addr.name = "北京顺义区"
addr.age = 24
-- print street with two style.
print(addr.street..addr["age"])
print(addr["street"], addr.name)


---------------------------------condition-----------------------------
if true then
print("if is true")
end
a = 1
if a == 1 then
print("if is true a == 1")
end

b = "happy"
if b == "sad" then
print("if b == \"sad\"")
else
print("else case.")
end

c = 3
if c == 1 then
print("if c==1 case")
elseif c ~= 2 then
print("elseif c is not equal to 2 case")
else
print("else case:"..tostring(c))
end

---------------------------------conditional assignments----------------
a = 1
-- it is same to b = (a == 1) ? "one" : "not one"
b = (a == 1) and "one" or "not one"
-- is equialent to
print("=(true or false) ?"..b)
--[[
a = 1
if a == 1 then
b = "one"
else
b = "not one"
end
print("=(true or false) ?"..b)
]]--
---------------------------------while----------------------------------
-- while statement. like while in C.
a = 10
while a > 0 do
print("while a:"..a)
a = a-1
end

-- repeat statement. like do .. while in C.
repeat
print("repeat a:"..a)
a = a+1
until a == 8

-- for statement.
-- numeric iteration form.
-- for a=start,end,step do statement end
for a=1,10, 2 do print("for a:"..a) end
-- Sequential iteration form.
for key, value in pairs({"k1", 1, "k2", 3, 6, "value3"})
do
-- key is index in pairs.
print(index, key, value)
end

a={1,2,3,"four",5.5, 6.6}
-- index is iteration for table(array in C) a.
for index, v in pairs(a)
do
print(index, v)
end

-----------------------------------break------------------------------
a = 0
while true do
a = a + 1
if a == 10 then
print("a is 10 break while.")
break
else
print("a is"..a.."no continue statement is running.")
end
end

print("a is "..a.."after while break.")

----------------------------------function-----------------------------
function func()
print("function func is called.")
return "func return string."
end

print(func())
a = func()
print("func ret is:"..a)
-- function with mutiple return variables.
function infomation(a, b, c)
print("function infomation is called with argument:",a,b,c)
return a,b,c, "return string in infomation."
end

a,b,c=1,2,3
a,b,c,d=infomation(a,b,c)
print(a,b,c,d)


-- global and local
-- local is local scope.
-- all variables are global in scope by default.
b = "global string for variable b."
function myfunc()
local b = "local string variable for variable b."
print(b)
a = "global string for variable a."
end
myfunc()
print(a)
-------------------------format------------------------------------
function printf(fmt, ...)
io.write(string.format(fmt, ...))
end

printf("Hello %s from %s in %s \n",
os.getenv("USER") or "NULL", _VERSION, os.date())


printf("int:(%d), string:(%s), double:(%.7f)\n",
100, "string test format", 3.1415926)

--------------------------build in library-------------------------
print("build in library test......")
print(math.sqrt(36), math.pi, math.rad(100), math.random())
print(math.exp(10+2))

--------------------------string operation-------------------------
str = "this is String."
-- return ASCII code of one char like %C in C.
print(str:byte(1).."-"..str:byte(3))
-- find the postion of substr in total string.
print(string.find(str, "is"))
print("strlen:"..string.len(str))
--repeat string 3 times.
print("string.rep:"..string.rep(str, 3))
--reverse string by every byte.
print("string.reverse:"..string.reverse(str))
-- to uppercase.
print("string.upper:"..string.upper(str))
-- to lowercase.
print("string.lower:"..string.lower(str))
--substr from index 2 to index 4.
print("string.sub:"..string.sub(str, 2, 4))
print("string.sub:"..string.sub(str, 1, -1))
print("string.sub:"..string.sub(str, 2, -3))
print("string.dump:"..string.dump(printf))
--------------------------table operation--------------------------
a = {2}
table.insert(a, 4)
table.insert(a, 7)
-- order by desc.
table.sort(a, function(v1, v2) return v1 > v2 end)
for i, v in ipairs(a) do print(i, v) end
--Returns the largest positive numerical index of the given table
print("max in table a is:"..table.maxn(a))
print("remove max number in table a is:"..table.remove(a, table.maxn(a)))
for i, v in ipairs(a) do print("after remove:"..i, v) end
table.concat(a, nil, 1, 2)
for i, v in ipairs(a) do print("after concat:"..i, v) end
--[[
--------------------------io operation-----------------------------
-- print seconds from 1970.01.01 to now
print("os.clock:"..os.clock())
print("os.time:"..os.time())
print("os.date():"..os.date())
-- print 12/08/13 21:11:00
print("os.date(%c):"..os.date("%c"))
t1=os.time()-20
t2=os.time()
-- get time inteval between two time t2,t1.
print("os.difftime():"..os.difftime(t2,t1))
-- it is same to system in C or exec in Tcl.
print("os.execute:"..os.execute("dir"))
-- exit
-- os.exit()
-- getenv
print("env PATH is:"..os.getenv("PATH"))
print("get tmpfile:"..os.tmpname())
--print(os.rename("1.txt", "2.txt"))
--print(os.remove("2.txt"))
-- write log function
function writelog(fmt, ...)
local log = io.open("log.2013", "a+")
log:write(string.format(fmt, ...))
log:flush()
io.close(log)
end
writelog("This is buffer:%s, int:%d\n", "log test", 1001)

-- dump file content function.
function dumpfile(fn)
local log = io.open(fn, "r")
for line in log:lines() do print(line) end
io.close(log)
end

dumpfile("log.2013")
]]--

格式化的时间串转成时间秒

function DateTime2Secs(timeStr)
    if string.find(timeStr, '-') and string.find(timeStr, '.') then
        local tab = {}
        tab["year"]  = string.sub(timeStr, 1,4)
        tab["month"] = string.sub(timeStr, 6,7)
        tab["day"]   = string.sub(timeStr, 9,10)
        tab["hour"]  = string.sub(timeStr, 12,13)
        tab["min"]   = string.sub(timeStr, 15,16)
        tab["sec"]   = string.sub(timeStr, 18,19)
        tab["isdst"] = false
        return os.time(tab)
    end
    return 0
end

如:

local timeSecs = Time2Secs("2016-09-27 13:38:49")
print(timeSecs)

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Win32下Qt与Lua交互使用(一):配置Qt下Lua运行环境发布时间:2022-07-22
下一篇:
ngx_lua配置及应用发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap