Lua is a simple and lightweight scripting language, examples from Lua official small examples, all learn to use
— Example 1 — Helloworld
Print it
-- Classic hello program.
print("helloworld")
-------- Output ------
hello
Copy the code
Example 2
There are two kinds of comments, two horizontal lines, and two square brackets for multi-line comments
-- Single line comments in Lua start with double hyphen.
--[[ Multiple line comments start with double hyphen and two square brackets. and end with two square brackets. ]]
-- And of course this example produces no
-- output, since it's all comments!
Copy the code
Example 3 — variables.
Variables are not declared, they are used directly, and there is no type HHH is similar to py
-- Variables hold values which have types, variables don't have types.
a=1
b="abc"
c={}
d=print
print(type(a))
print(type(b))
print(type(c))
print(type(d))
-------- Output ------
number
string
table
function
Copy the code
— Example 4 — variable name.
Note: Same as C
-- Variable names consist of letters, digits and underscores.
-- They cannot start with a digit.
one_two_3 = 123 -- is valid varable name
-- 1_two_3 is not a valid variable name.
Copy the code
Variable names can be alphanumeric and underscore but must not start with a number
— Reserved words.
It starts with underscore
-- The underscore is typically used to start special values
-- like _VERSION in Lua.
print(_VERSION)
-- So don't use variables that start with _,
-- but a single underscore _ is often used as a
-- dummy variable.
-------- Output ------
Lua 5.1
Copy the code
An underscore is the beginning of reserved words. Variables cannot begin with _
Example 6 — Case sensitive.
Don’t have to explain
-- Lua is case sensitive so all variable names & keywords
-- must be in correct case.
ab=1
Ab=2
AB=3
print(ab,Ab,AB)
-------- Output ------
1 2 3
Copy the code
Case sensitive
— Example 7 — reserved keywords.
Capitalized is not a keyword
-- Lua reserved words are: and, break, do, else, elseif,
-- end, false, for, function, if, in, local, nil, not, or,
-- repeat, return, then, true, until, while.
-- Keywords cannot be used for variable names,
-- 'and' is a keyword, but AND is not, so it is a legal variable name.
AND=3
print(AND)
-------- Output ------
3
Copy the code
— Example 8 — string
3, single quotes, double quotes, and multiple lines (multiple lines with newlines)
a="single 'quoted' string and double \"quoted\" string inside"
b='single \'quoted\' string and double "quoted" string inside'
c= [[ multiple line
with 'single'
and "double" quoted strings inside.]]
print(a)
print(b)
print(c)
-------- Output ------
single 'quoted' string and double "quoted" string inside
single 'quoted' string and double "quoted" string inside
multiple line
with 'single'
and "double" quoted strings inside.
Copy the code
Three ways to represent a string
— Example 9 — strange assignment methods are supported
-- a,b = b,a is valid
a,b,c,d,e = 1.2.3.'four'.'five'
print(a,b,c,d,e)
-------- Output ------
1 2 3 four five
Copy the code
— Example 10 — a strange way to assign values is to swap variables
-- Multiple assignments allows one line to swap two variables.
print(a,b)
a,b=b,a
print(a,b)
-------- Output ------
1 2
2 1
Copy the code
— The number of people in the world
You can connect strings and numbers with two dots
-- Multiple assignment showing different number formats.
-- Two dots (..) are used to concatenate strings (or a
-- string and a number).
a,b,c,d,e = 1.1.123.1E9.- 123..0008.
print("a="..a, "b="..b, "c="..c, "d="..d, "e="..e)
-------- Output ------
a=1 b=1.123 c=1000000000 d=- 123. e=0.0008
Copy the code
— Example 12 — print without parentheses?
-- More writing output.
print "Hello from Lua!"
print("Hello from Lua!")
-------- Output ------
Hello from Lua!
Hello from Lua!
Copy the code
— Example 13 — can use stdout
-- io.write writes to stdout but without new line.
io.write("Hello from Lua!")
io.write("Hello from Lua!")
-- Use an empty print to write a single new line.
print(a)-------- Output ------Hello from Lua! Hello from Lua!Copy the code
Print can print a new line
— Example 14 — array.
Array, officially written Tables, can be accessed using subscripts
-- Simple table creation.
a={} -- {} creates an empty table
b={1.2.3} -- creates a table containing numbers 1,2,3
c={"a"."b"."c"} -- creates a table containing strings a,b,c
print(a,b,c) -- tables don't print directly, we'll get back to this!!
-------- Output ------
table: 008A48A8 table: 008A4420 table: 008A4768
The default initial index of a table in Lua usually starts with 1.
> b = {4.5.6.7.8}
> print(b)
table: 009B9978
> print(b[0])
nil
> print(b[1])
4
> print(b[2])
5
Copy the code
— Example 15 subscripts can be strings
-- Associate index style.
address={} -- empty address
address.Street="Wyman Street"
address.StreetNumber=360
address.AptNumber="2a"
address.City="Watertown"
address.State="Vermont"
address.Country="USA"
print(address.StreetNumber, address["AptNumber"])
-------- Output ------
360 2a
Copy the code
— Example 16 — if statement.
Remember then and end
-- Simple if.
a=1
if a==1 then
print ("a is one")
end
-------- Output ------
a is one
Copy the code
— Example 17 — if else statement.
if else end
b="happy"
if b=="sad" then
print("b is sad")
else
print("b is not sad")
end
-------- Output ------
b is not sad
Copy the code
if then else end
— Example 18 — if elseif else statement
Many branches
c=3
if c==1 then
print("c is 1")
elseif c==2 then
print("c is 2")
else
print("c isn't 1 or 2, c is ".tostring(c))
end
-------- Output ------
c isn't 1 or 2, c is 3
Copy the code
if then elseif then else end
— Example 19 — Conditional assignment?
It’s kind of like the triadic operator for C
Is b = (a == 1)? “one”: “not one”;
-- value = test and x or y
a=1
b=(a==1) and "one" or "not one"
print(b)
-- is equivalent to
a=1
if a==1 then
b = "one"
else
b = "not one"
end
print(b)
-------- Output ------
one
one
Copy the code
— Example 20 — while
While do end (~= = C! =)
a=1
while a~=5 do -- Lua uses ~= to mean not equal
a=a+1
io.write(a.."")
end
-------- Output ------
2 3 4 5
Copy the code
— Example 21 — repeat until statement.
do while?
a=0
repeat
a=a+1
print(a)
until a==5
-------- Output ------
1
2
3
4
5
Copy the code
— Example 22 — for loop
For [1, 4] do end
-- Numeric iteration form.
-- Count from 1 to 4 by 1.
for a=1.4 do io.write(a) end
print(a)-- Count from 1 to 6 by 3.
for a=1.6.3 do io.write(a) end
-------- Output ------
1234
14
Copy the code
for do end
— Example 23 — Foreach? .
For can also use *(foreach?)
-- Sequential iteration form.
for key,value in pairs({1.2.3.4}) do print(key, value) end
-------- Output ------
1 1
2 2
3 3
4 4
Copy the code
Example 24 — Prints an array with pairs.
pairs?
-- Simple way to print tables. ## iterator
a={1.2.3.4."five"."elephant"."mouse"}
for i,v in pairs(a) do print(i,v) end
-------- Output ------
1 1
2 2
3 3
4 4
5 five
6 elephant
7 mouse
Copy the code
— Example 25 — break out of the loop
-- break is used to exit a loop.
a=0
while true do
a=a+1
if a==10 then
break
end
end
print(a)
-------- Output ------
10
Press 'Enter' key for next example
Copy the code
— Example 26 — function
-- Define a function without parameters or return value.
function myFirstLuaFunction(a)
print("My first lua function was called")
end
-- Call myFirstLuaFunction.
myFirstLuaFunction()
-------- Output ------
My first lua function was called
Copy the code
Example 27 — a function that returns a value
-- Define a function with a return value.
function mySecondLuaFunction(a)
return "string from my second function"
end
-- Call function returning a value.
a=mySecondLuaFunction("string")
print(a)
Copy the code
— Example 28 — returns a bunch of values
-- Define function with multiple parameters and multiple return values.
function myFirstLuaFunctionWithMultipleReturnValues(a,b,c)
return a,b,c,"My first lua function with multiple return values".1.true
end
a,b,c,d,e,f = myFirstLuaFunctionWithMultipleReturnValues(1.2."three")
print(a,b,c,d,e,f)
-------- Output ------
1 2 three My first lua function with multiple return values 1true
Copy the code
— Example 29 — local
Default variables are global variables, and local variables are declared with local
-- All variables are global in scope by default.
b="global"
-- To make local variables you must put the keyword 'local' in front.
function myfunc(a)
local b=" local variable"
a="global variable"
print(a,b)
end
myfunc()
print(a,b)
-------- Output ------
global variable local variable
global variable global
Copy the code
All variables are global in scope by default.
— Example 30 — Format printf
-- An implementation of printf.
function printf(fmt, ...)
io.write(string.format(fmt, ...) )end
printf("Hello %s from %s on %s\n".os.getenv"USER" or "there"._VERSION.os.date())
-------- Output ------
Hello there from Lua 5.1 on 08/05/19 09:34:49
Copy the code
Example 31 standard library?
--[[ Standard Libraries Lua has standard built-in libraries for common operations in math, string, table, input/output & operating system facilities. External Libraries Numerous other libraries have been created: sockets, XML, profiling, logging, unittests, GUI toolkits, web frameworks, and many more. ]]
-------- Output ------
Copy the code
— Example 32 — Math library.
-- Math functions:
-- math.abs, math.acos, math.asin, math.atan, math.atan2,
-- math.ceil, math.cos, math.cosh, math.deg, math.exp, math.floor,
-- math.fmod, math.frexp, math.huge, math.ldexp, math.log, math.log10,
-- math.max, math.min, math.modf, math.pi, math.pow, math.rad,
-- math.random, math.randomseed, math.sin, math.sinh, math.sqrt,
-- math.tan, math.tanh
print(math.sqrt(9), math.pi)
-------- Output ------
3 3.1415926535898
Copy the code
— Example 33 — String library.
-- String functions:
-- string.byte, string.char, string.dump, string.find, string.format,
-- string.gfind, string.gsub, string.len, string.lower, string.match,
-- string.rep, string.reverse, string.sub, string.upper
print(string.upper("lower"),string.rep("a".5),string.find("abcde"."cd"))
-------- Output ------
LOWER aaaaa 3 4
Copy the code
— Example 34 — Table library.
-- Table functions:
-- table.concat, table.insert, table.maxn, table.remove, table.sort
a={2}
table.insert(a,3);
table.insert(a,4);
table.sort(a,function(v1,v2) return v1 > v2 end)
for i,v in ipairs(a) do print(i,v) end
-------- Output ------
1 4
2 3
3 2
Copy the code
— Example 35 — Input /output library.
-- IO functions:
-- io.close , io.flush, io.input, io.lines, io.open, io.output, io.popen,
-- io.read, io.stderr, io.stdin, io.stdout, io.tmpfile, io.type, io.write,
-- file:close, file:flush, file:lines ,file:read,
-- file:seek, file:setvbuf, file:write
print(io.open("file doesn't exist"."r"))
-------- Output ------
nil file doesn't exist: No such file or directory 2Copy the code
— Example 36 — OS library
-- OS functions:
-- os.clock, os.date, os.difftime, os.execute, os.exit, os.getenv,
-- os.remove, os.rename, os.setlocale, os.time, os.tmpname
print(os.date())
-------- Output ------
08/05/19 09:36:36
Copy the code
— Example 37 — External libraries
External libraries need to be imported using require
-- Lua has support for external modules using the 'require' function
-- INFO: A dialog will popup but it could get hidden behind the console.
require( "iuplua" )
ml = iup.multiline
{
expand="YES",
value="Quit this multiline edit app to continue Tutorial!",
border="YES"
}
dlg = iup.dialog{ml; title="IupMultiline", size="QUARTERxQUARTER",}
dlg:show()
print("Exit GUI app to continue!")
iup.MainLoop()
-------- Output ------
failed to load & run sample code
error loading module 'iuplua' from file 'C:\Dev\Lua\clibs\iuplua51.dll':
The specified module could not be found.
Copy the code
There are many examples of this
--[[ To learn more about Lua scripting see Lua Tutorials: http://lua-users.org/wiki/TutorialDirectory "Programming in Lua" Book: http://www.inf.puc-rio.br/~roberto/pil2/ Lua 5.1 Reference Manual: Start/designed / / Documentation/Lua Lua 5.1 Reference Manual Examples: Start/Examples/designed/Lua]]
Copy the code