# What is lua script

Quoted from:https://www.runoob.com/lua/

# Introduction to the lua language

Overview

Lua is a lightweight scripting language, written in standard C woth open source code, designed to be embedded in applications to provide flexible extension and customization.

Traits

lightweight, flexible extension and etc.

  • Lightweight: It is written in standard C language and open in source code form. File size around 100 kilobytes after compiled, which can be easily embedded in other programs.
  • Flexible extension: Lua provides easy to use extension interfaces and mechanisms: these functions are provided by the host language (usually C or C++), and Lua can use them as if they were already built in.
  • Other features:
    • Support procedure-oriented and functional programming);
    • Automatic memory management; Only one generic type of table is provided, which can implement arrays, hash tables, collections and objects;
    • Language built-in pattern matching;Closure; The function can also be viewed as a value; Support for multi-threading (collaborative processes, not threads supported by the operating system);
    • Closures and tables make it easy to support some of the key mechanisms required for object-oriented programming, such as data abstraction, virtual functions, inheritance, and overloading.

Implementation:

  1. Game development
  2. Apply scripts independently
  3. Web application scripts
  4. Extensions and database plug-ins such as MySQL Proxy and MySQL WorkBench
  5. Security systems, such as intrusion detection systems

::: Please note:

In the following cases, we will be using only 1 API: Chat:sendSystemMsg, which output text in chat box in game. You can copy the code in game to see the result in chat box. :::

# Lua Basic Syntax

Annotations

Single line annotation: --

-- Content after this won't be executed

Annotations

Multi-line annotation:

--[[
Content included won't be executed.
--]]

Identifier

What is identifier:

1. The Lua identifier is used to define a variable, and the function obtains other user-defined items.
2. An identifier begins with letter A to Z or a to z or an underscore _ followed by 0 or more letters, underscores, and Numbers (0 to 9).
3. It is best not to use underscores and captial letters as identifiers, because it will be the same as Lua reserved words.
4. Lua does not allow the use of Special characters such as @, $, and % cannot use in Lua as identifiers.
5. Therefore, in Lua, Miniworld and miniworld are two different identifiers.

Identifier

Correct term:

mini   world   abc   mini_world  a_123
mini521   _mini  c   mi5ni2   MiNi

Keywords

The reserved Lua keywords are listed below.The reserved keyword cannot be used as a constant or variable or as another user-defined identifier: **

and break do else elseif end false for function if
in local nil not or repeat return then true until
while goto

Global Variable

By default, variables are always considered global. There is no need to declare a global variable, a global variable is created by assigning a value to a variable, and there is no error in accessing an undeclared global variable, only the result will be nil.

Chat:sendSystemMsg(b , 0) --undeclared variable b, no error, but the printed result is nil
------------------
b=10
Chat:sendSystemMsg(b , 0) --declared variable b, the printed result of b is 10
------------------
--If you want to delete a global variable, just assign nil as value
b = nil
Chat:sendSystemMsg(b , 0)
--So it's like the variable b has never been used. In other words, a variable only exists when it is not equal to nil.

# Lua Data Type

Data Name Description
nil an invalid value(The equivalent of false in a conditional expression)
boolean boolean value containing two values: false and true
number A real number, representing a real floating point number of type double, or an integer
string A string, represented by a pair of single or double quotes
table A data structure of Lua, used to create different data types, such as arrays, dictionaries, and etc
function Functions written by C or Lua
userdata Represents any C data structure stored in a variable
thread Represents a separate line of execution used to execute a coroutine

# Lua Variables

Variables Overview

What is variable?

  1. Before a variable can be used, it must be declared in the code to create it.
  2. Before the compiler can execute the code, it needs to know how to store the values of the statement variables.
  3. There are three types of Lua variables: global, local, and fields in a table.
  4. The variables in Lua are all global variables, even in statement blocks or functions, unless they are explicitly declared as local variables.
  5. Local variables are scoped from the declaration location to the end of the statement block.
  6. The default value of all variables is nil.
 




















a = 5               -- global variable
local b = 5         -- local variable
--------------
function joke()		-- define variable
    c = 5           -- global variable
    local d = 6     -- local variable
end
--------------
joke()
Chat:sendSystemMsg(c,0)          --> 5
Chat:sendSystemMsg(d,0)          --> nil


do 
    local a = 6     -- local variable
    b = 6           -- Reassign a local variable
    Chat:sendSystemMsg(a,0);     --> 6
    Chat:sendSystemMsg(b,0);     --> 6
end
print(a,b)      --> 5 6

How to Assign Value赋值语句

Assignment is the most basic way to change the value of a variable and change a table field.

a = "hello" .. "world"
--Multiple variables are assigned at the same time. The elements of the list of variables and the list of values are separated by commas. The values on the right side of the assignment statement are assigned to the left variable in turn
a, b = 10, 2*x 
--Lua will evaluate all the values on the right before performing the assignment, so we can exchange the values of variables by:
x, y = y, x                    
a[i], a[j] = a[j], a[i] 

Note

When the number of variables and the number of values are inconsistent, Lua will always take the following strategy based on the number of variables:

  1. The number of variables > the number of values, Make up nil by the number of variables
  2. The number of variables < the number of values, Redundant values are ignored
a, b, c = 0, 1
Chat:sendSystemMsg(a,0)     --> 0
Chat:sendSystemMsg(b,0)     --> 1
Chat:sendSystemMsg(c,0)     --> nil
 
a, b, c = 0, 1 
a, b = a+1, b+1, b+2  
Chat:sendSystemMsg(a,0)     --> 1
Chat:sendSystemMsg(b,0)     --> 2

a, b, c = 0
Chat:sendSystemMsg(a,0)   		   --> 0
Chat:sendSystemMsg(b,0)            --> nil
Chat:sendSystemMsg(c,0)            --> nil
--The last example is a common error case. Becareful that if you want to assign values to multiple variables, you must assign values to each variable in turn.
a, b = f()
--Multivalued assignments are often used to swap variables or return function calls to variables
--f() returns two values, the first to a and the second to b.
--Local variables should be used whenever possible, with two benefits:

--1. Avoid naming conflicts.
--2. Local variables are accessed faster than global variables.

Indes

Use square brackets [] for the index of the table.Lua also provides the. Operation.

t[i]
t.i                 -- A simplified way of writing when the index is string
gettable_event(t,i) -- Using index access is essentially a function call like this
 site = {}
 site["key"] = "www.mini1.com"
 Chat:sendSystemMsg(site["key"],0)
--example
 Chat:sendSystemMsg(site.key , 0)

# Lua Loop Statement

No. Control Statement Description
1 while When the condition is true, have the program execute certain statements repeatedly.The condition is checked for true before the statement is executed.
2 for Repeats the specified statement. The number of repeats can be controlled in the for statement.
3 repeat...until Repeat the loop until the specified condition is true
4 NestLoop You can nest one or more loop statements inside a loop (while do...The end;The for...The do...The end;Repeat...Until;)
No. Control Statement Description
1 break Exits the current loop or statement and starts the script to execute the following statement.
2 goto Moves the control point of the program to a label.

while

--Example:
--The following example loops out the value of a in the chat box
a = 0
while( a < 5 )  --execute content in do when a<5
do
   Chat:sendSystemMsg( a, 0)  --output value of a in the chat box
   a = a+1  --Each loop plus 1 to a
end
--Output result:
-- 0 
-- 1
-- 2
-- 3
-- 4

for

Numerical Value for Loop:

for var=a , b , c do
--executionbody-- end

Var changes from a to b, each change is incremented by var with step c, and the "execution body" is executed once. c is optional and defaults to 1 if not specified.

--Example:
--Simple for loop, output the value of I in the chat box:
for i = 1 , 5 , 1  do 
	Chat:sendSystemMsg( i, 0)
end 
--Output result:
-- 1
-- 2
-- 3
-- 4
-- 5

Generic for Loop:

Generic for Loop iterate through all the values through an iterator function, similar to the foreach statement in Java.

--Example:
--Print all the values of the array a

a = {"one", "two", "three"}
for i, v in ipairs(a) do
	Chat:sendSystemMsg( v, 0)
end 

--I is the array index value, and v is the array element value corresponding to the index.Ipairs is an iterator function provided by Lua to iterate over arrays.

repeat...until

Overview:

In Lua, repeat...until is different from for and while loop, the conditional statement of for and while loop is judged at the beginning of the current loop execution, while repeat...until loop is judged at the end.

--Example:
--Prints the value of a in the chat box
a = 0
--[ execute loop --]
repeat
	Chat:sendSystemMsg( a, 0)
   a = a + 1
until( a > 5 )  --Loop until a>5
--Output result:
-- 0
-- 1
-- 2
-- 3
-- 4
-- 5

Nestloop

Overview

The Lua allows loop to be embedded in loops. We can also use different loop types for nesting, such as a while loop nested in the body of a for loop.

--Example:
--Output value of i and j in chat box

for i = 1 , 2 , 1 do
   for j = 1, 2 , 1 do

		Chat:sendSystemMsg( i, 0)
		Chat:sendSystemMsg( j, 0)
      end
   end
end
--Output result:
-- 1
-- 1
-- 1
-- 2
-- 2
-- 1
-- 2
-- 2

break Statement

Break statement

  1. The Lua break statement is inserted into the body of the loop to exit the current loop or statement and execute the following statement
  2. If you use loop nesting, the break statement will stop the execution of the innermost loop and start the execution of the outer loop.
--the following example executes the while loop, outputs the value of a when a is less than 20, and terminates the loop when a is greater than 15:

--[ defined variable --]
a = 10
--[ while loop --]
while( a < 20 )
do
	Chat:sendSystemMsg( a, 0)
   a=a+1
   if( a > 15)
   then
      --[ use break statement to exit loop --]
      break
   end
end
--Output result:
-- 10
-- 11
-- 12
-- 13
-- 14 
-- 15

goto Statement

goto Statement

The goto statement in the Lua allows the control flow to be moved unconditionally to the marked statement.

local a = 1
::start:: Chat:sendSystemMsg("where goto located",0)

a = a+1
if a < 3 then
    goto start   -- go to lable start, when a is less than 3
end
--Output result:
-- where goto located
-- where goto located

# Flow control statement (conditional statement)

Overview:

1.The Lua flow control statement is set by programmatically setting one or more conditional statements.Executes the specified code when the condition is true, and any other specified code when the condition is false. 2. The conditional expression result of the control structure can be any value. In lua, false and nil are both false, true and non nil is true. 3. In lua, 0 is true:

--[ 0 is true ]
if(0)
then
	Chat:sendSystemMsg("0 is true", 0)
end
No. Statement Descriptions
1 if Statement if statement consists of a Boolean expression as a conditional judgment followed by other statements.
2 if...else Statement if can be used with an else statement, execute else when the if condition expression is false.
3 if nest Statement You u can use one or more if or else if statements in if or else if statement.

if Statement

if Statement

Lua if statement consists of a Boolean expression as a conditional judgment followed by other statements.

--The following example is used to determine whether the value of variable a is less than 20:
--[ defined variable --]
a = 10;

--[ use if statement --]
if( a < 20 )
then
   --[ print the info below when if is true --]
   Chat:sendSystemMsg("a is less than 20" , 0);
end

Chat:sendSystemMsg( "value of a is:"..a.."", 0);

--Output result:
--a is less than 20
--value of a is:10

if...else Statement

if...else Statement

In lua if statement can be used with an else statement to execute an else statement block if the conditional expression is false.

--The following example is used to determine the value of variable a:
a = 100;
--[ check the condition --]
if( a < 20 )
then
   --[ execute statement block when if is true --]
   Chat:sendSystemMsg("a is less than 20",0 )
else
   --[ execute statement block when if is false --]
   Chat:sendSystemMsg("a is greater than 20",0 )
end
Chat:sendSystemMsg("value of a is:"..a.."", 0)

--Output result:
--a is greater than 20
--value of a is:100

if...elseif...else Statement

In lua if statement can be used with elseif...else, execute elseif...else statement block when if is false, to detects multiple conditional statements.

--The following example determines the value of variable a:
--[ defined variable --]
a = 100

--[ Check Boolean conditions --]
if( a == 10 )
then
   --[ Print the following info if condition is true --]
   Chat:sendSystemMsg("value of a is 10" ,0)
elseif( a == 20 )
then   
   --[ Print the following when condition of if else if is true --]
   Chat:sendSystemMsg("value of a is 20" ,0)
elseif( a == 30 )
then
   --[ Print the following when condition of if else if condition is true  --]
   Chat:sendSystemMsg("value of a is 30" ,0)
else
   --[ Print the following when no statements condition is true --]
   Chat:sendSystemMsg("There is no value that matches a" ,0)
end
Chat:sendSystemMsg("value of a is:".. a .."", 0)

if Nest Statement

if Nest Statement

In Lua, if statement allows nesting, which means you can insert other if or else if statements into if or else if statement.

--The following example is used to determine the values of variables a and b and output them in the chat box:
--[ defined variable --]
a = 100;
b = 200;

--[ Check Condition --]
if( a == 100 )
then
   --[ When if condition is true, judge the the following if condition --]
   if( b == 200 )
   then
      --[ Execute the following statement block when condition of if is true --]
      Chat:sendSystemMsg("value of a is 100, value of b is 200" );
   end
end
Chat:sendSystemMsg("value of a is:" .. a.."", 0);
Chat:sendSystemMsg("value of b is:".. b .."", 0 );

# Lua Function

What is Lua Function

In Lua, functions are the main way to abstract statements and expressions. It can be used either for special tasks or for calculating values.

  • Lua provides a number of built-in functions that you can easily use, such as the print() function to prints results.
  • Lua function serves two main purposes:
    • Completes the specified task, in which case the function is used as a calling statement;
    • Calculate and returns a value, in which case the function is used as an expression for an assignment statement.

Function Definitions:

Lua functions are defined in the following format:

optional_function_scope function function_name( argument1, argument2, argument3..., argumentn)
    function_body
    return result_params_comma_separated
end

Code Dissected:

  • optional_function_scope: This parameter is optional to specify whether the function is a global or a local function. Without setting this parameter, it defaults to a global function. If you need to set the function as a local function, you need to use the keyword local.
  • function_name: Specify the function name.
  • argument1, argument2, argument3..., argumentn: Function parameters, multiple parameters separated by commas, functions can also take no parameters.
  • function_body: Function body, a code block that needs to be executed in a function.
  • result_params_comma_separated: The Lua language function can return multiple values, each separated by a comma.

Example 1:

The following example defines the function max (), parameters are num1 and num2 to compare the values and return the maximum value:

--[[ The function returns the greater value of the two --]]
function max(num1, num2)

   if (num1 > num2) then
      result = num1;
   else
      result = num2;
   end

   return result; 
end
-- call function
Chat:sendSystemMsg("The greater value of the comparison is:"..max(10,4).."",0)
Chat:sendSystemMsg("The greater value of the comparison is:"..max(5,6).."",0)

Example 2: In Lua, we can pass the function as a parameter to the function, as shown in the following example:

myprint = function(param)
   Chat:sendSystemMsg("value of parameter:" ..param.. "",0)

end

function add(num1,num2,functionPrint)
   result = num1 + num2
   --  Call the passed function parameter
   functionPrint(result)
end
myprint(10)
-- myprint  function is passed as an argument
add(2,5,myprint)

Return Multiple Value

Lua function can return multiple value, such as string.find, It returns the matching string "subscripts at the beginning and the end(return nil if no result).

Example: In the Lua function, multiple values can be returned by the value list after return, for example:

function maximum (a)
    local mi = 1             -- max value index
    local m = a[mi]          -- max value
    for i,val in ipairs(a) do
       if val > m then
           mi = i
           m = val
       end
    end
    return m, mi
end
print(maximum({8,10,23,12,5}))
--Since the Chat:sendSystemMsg can only output one value, you can only print to see the return value

Variable Parameter

Lua functions can accept a variable number of arguments, similar to the C language, using three points in the function argument list...Means that the function has variable arguments.

Example 1: Splicing

-- Because function Chat:sendSystemMsg prints only 1 value, there is no way to output 2 returned values
-- We can do splicing with variable parameters
function dump_args(...)
        local buffer = ''
        local size = select('#', ...)
    for idx = 1, select('#', ...) do
            local arg = select(idx, ...)
            local ends = idx==size and "" or ", "
            buffer = buffer..tostring(arg)..ends
    end
    return buffer
end
function maximum (a)
    local mi = 1             -- max value index
    local m = a[mi]          -- max value
    for i,val in ipairs(a) do
       if val > m then
           mi = i
           m = val
       end
    end
    return m, mi
end

Chat:sendSystemMsg(dump_args(maximum({8,10,23,12,5})),0)
--By calling the variable parameter dump_args, you can print out multiple function return values

Example 2: Obtain Average Value

function average(...)
   result = 0
   local arg={...}    --> arg is a table, local variable
   for i,v in ipairs(arg) do
      result = result + v
   end
   Chat:sendSystemMsg("Total incoming of" .. #arg .. " number",0)
   return result/#arg
end
Chat:sendSystemMsg("average number is" ..average(10,5,3,4,5,6).. " ",0)

Example 3: Obtain Average Value

---we can also use select("#",...) to obtain the number of variable parameter:

function average(...)
   result = 0
   local arg={...}
   for i,v in ipairs(arg) do
      result = result + v
   end
   print("Total incoming of" .. select("#",...) .. " number")
   return result/select("#",...)
end
Chat:sendSystemMsg("average number is"..average(10,5,3,4,5,6).." ",0)

# Lua Operator

Operator Definitions:

OOperators are special characters that tells the interpreter to perform a specific mathematical or logical operation.Lua provides the following types of Character:

arithmetic operator

The following table lists the commonly used arithmetic operators in the Lua language, setting the value of a to 10 and the value of b to 20:

Operator Description Example
+ add A + B output 30
- minus A - B output -10
* times A * B output 200
/ division B / A woutput 2
% remainder B % A output 0
^ power A^2 output 100
- negative sign -A output -10

Example : We can understand the application of arithmetic operators better through the following examples:

a = 21
b = 10
c = a + b
print(" value of Line 1 - c is ", c )
c = a - b
print("value of Line 2 - c is ", c )
c = a * b
print("value of Line 3 - c is ", c )
c = a / b
print("value of Line 4 - c is ", c )
c = a % b
print("value of Line 5 - c is ", c )
c = a^2
print("value of Line 6 - c is ", c )
c = -a
print("value of Line 7 - c is ", c )
--Print result:
--value of Line 1 - c is     31
--value of Line 2 - c is     11
--value of Line 3 - c is     210
--value of Line 4 - c is     2.1
--value of Line 5 - c is     1
--value of Line 6 - c is     441
--value of Line 7 - c is     -21

relational operator

The following table lists the commonly used relational operators in Lua language, setting the value of a to 10 and the value of b to 20:

Operator Description Example
== equal to. checks whether the two values are equal, if equal returns true, if not return false (A == B) as false.
~= not equal to. checks whether the two values are equal,if equal returns false, if not return true (A ~= B) as true.
> great than. check if the value on the left is greater than the value on the right. If yes return true, if not return false (A > B) as false.
< less than. check if the value on the left is greater than the value on the right. If yes return false, if not return true (A < B) as true.
>= equal or great than. check if the value on the left is equal or greater than the value on the right. If yes return true, if not return false (A >= B) as false.
<= equal or less than. check if the value on the left is equal or less than the value on the right. If yes return false, if not return false (A <= B) as true.

Example : We can understand the application of relational operator better through the following examples:

a = 21
b = 10

if( a == b )
then
   print("Line 1 - a equals to b" )
else
   print("Line 1 - a not equal to b" )
end

if( a ~= b )
then
   print("Line 2 - a not equal to b" )
else
   print("Line 2 - a equals to b" )
end

if ( a < b )
then
   print("Line 3 - a is less than b" )
else
   print("Line 3 - a is greater than or equal to b" )
end

if ( a > b ) 
then
   print("Line 4 - a is greater than b" )
else
   print("Line 5 - a is less than or equal to b" )
end

-- Modify the values of a and b
a = 5
b = 20
if ( a <= b ) 
then
   print("Line 5 - a is less than or equal to b" )
end

if ( b >= a ) 
then
   print("Line 6 - b is greater than or equal to a" )
end
--Execution Result:
--Line 1 - a not equal to b
--Line 2 - a not equal to b
--Line 3 - a is greater than or equal to b
--Line 4 - a is greater than b
--Line 5 - a is less than or equal to  b
--Line 6 - b is greater than or equal to a

logical operator

Operator Description Example
and AND operator. If a is false, return a, otherwise return b. (A and B) is false.
or OR operator. If a is true, returns A, otherwise returns b. (A or B) is true.
not NOT operator. The opposite of a logical operation. If condition is true, the logic is not false. not(A and B) is true.

Example: We can understand the application of logical operator better through the following examples:

a = true
b = true

if ( a and b )
then
   print("a and b - condition is true" )
end

if ( a or b )
then
   print("a or b - condition is true" )
end

print("---------separateline---------" )

-- Modify the values of a and b
a = false
b = true

if ( a and b )
then
   print("a and b - condition is true" )
else
   print("a and b - condition is false" )
end

if ( not( a and b) )
then
   print("not( a and b) - condition is true" )
else
   print("not( a and b) - condition is false" )
end
--Execution Result:
--a and b - condition is true
--a or b - condition is true

--a and b - condition is false
--not( a and b) - condition is true

other operators

The following table lists the concatenation operator and the operators that calculate the length of the table or string:
Operator Description Example
.. connect 2 string a..b , a is "Hello " , b is "World", output result is "Hello World".
# Unary operator that returns the length of a string or table. #"Hello" returns 5

Example:

We can understand the application of concatenation and calculate operator better through the following examples:

a = "Hello "
b = "MiniWorld"

print("connect a and b ", a..b )

print("b string length ",#b )

print("string length Test",#"Test" )

print("Mini World official site length",#"https://www.miniworldgame.com/" )
--Execution Result:
--connect string a and b 	Hello MiniWorld
--b string length     10
--string length Test     4
--Mini World official site length	30

Operator precedence

Order from high to low:

^
not    - (unary)
*      /
+      -
..
<      >      <=     >=     ~=     ==
and
or

Except for ^ and.. All binary operators are left concatenated.

a+i < b/2+1          <-->       (a+i) < ((b/2)+1)
5+x^2*8              <-->       5+((x^2)*8)
a < y and y <= z     <-->       (a < y) and (y <= z)
-x^2                 <-->       -(x^2)
x^y^z                <-->       x^(y^z)

Example: We can understand the application of Operator precedence better through the following examples:

a = 20
b = 10
c = 15
d = 5

e = (a + b) * c / d;-- ( 30 * 15 ) / 5
print("(a + b) * c / d operation value is:",e )

e = ((a + b) * c) / d; -- (30 * 15 ) / 5
print("((a + b) * c) / d operation value is:",e )

e = (a + b) * (c / d);-- (30) * (15/5)
print("(a + b) * (c / d) operation value is:",e )

e = a + (b * c) / d;  -- 20 + (150/5)
print("a + (b * c) / d operation value is:",e )
--Execution Result:
--(a + b) * c / d operation value is:    90.0
--((a + b) * c) / d operation value is:    90.0
--(a + b) * (c / d) operation value is:    90.0
--a + (b * c) / d operation value is:   50.0

# Lua String

Overview::

String is characters composed of numbers, letters, and underscores. In Lua, strings can be represented in the following three ways:

  • A string of characters between single quotes.
  • A string of characters between double quotes.
  • A string of characters between [[and]]. Example:
string1 = "Lua"
print("\"String 1 is\"",string1)
string2 = 'https://www.miniworldgame.com/'
print("String 2 is",string2)
string3 = [["Lua tutorials"]]
print("String 3 is",string3)

--Output result:
--"String 1 is"    Lua
--String 2 is    https://www.miniworldgame.com/
--String 3 is    "Lua tutorials"

Escape characters are used to represent characters that cannot be displayed directly, such as return, enter and etc. You can use "\ "" if in string to convert double quotes.

Escape character Desciption ASCII code value (decimal)
\a bell (BEL) 007
\b backspace (BS), move the current position to the previous column 008
\f change page (FF), move the current position to the beginning of the next page 012
\n line feed (LF), move the current position to the beginning of the next line 010
\r press enter (CR) to move the current position to 013 at the beginning of the line
\t horizontal TAB (HT) (skip to the next TAB position) 009
\v vertical TAB (VT) 011
\ represents a backslash character '' 092
' represents a single quotation mark (apostrophe) character 039
" represents a double quotation mark character 034
\0 NULL character (NULL) 000
\ DDD 1 to 3 octal number represented by any character three octal
\ XHH 1 to 2 bits of hexadecimal represented by any character 2 bits of hexadecimal

String Executions

In Lua, there are many format to support execution of string:
No. Format & Application
1 string.upper(argument):
Convert all characters in string to captial letters
2 string.lower(argument):
Convert all characters in string to lower case letters.
3 string.gsub(mainString,findString,replaceString,num)
replace in string.
mainString Is the string to execute on, findString is the replaced character, replaceString is the character to be replaced, num is the number of replacement(if ignore, then replace all), example:
string.gsub("aaaa","a","z",3)
zzza 3
4 string.find (str, substr, [init, [end]])
Searches specified content in specified string (the third parameter is the index), returning its specific location.Nonexistence returns nil. Return nil if no search result.
string.find("Hello Lua user", "Lua", 1)
7 9
5 string.reverse(arg)
reverse string
string.reverse("Lua")
auL
6 string.format(...)
Returns a formatted string similar to print
string.format("the value is:%d",4)
the value is:4
7 string.char(arg) 和 string.byte(arg[,int])
Convert integer numbers into string and connect them, byte converts string to integer values(can specify a character, default to the first character).
string.char(97,98,99,100)
abcd
string.byte("ABCD",4)
68
> string.byte("ABCD")
65
8 string.len(arg)
Calculate string length.
string.len("abc")
3
9 string.rep(string, n)
Returns n copies of the string
string.rep("abcd",2)
abcdabcd
10 ..
Connect 2 strings
print("www.mini1.".."cn")
www.mini1.cn
11 string.gmatch(str, pattern)
Returns an iterator function that, each time it is called, returns the next captures from parttern over strings.If pattern specifies no captures, then the whole match is produced in each call. Return nil when there is no capture.
for word in string.gmatch("Hello Lua user", "%a+") do print(word) end
Hello
Lua
Lua
12 string.match(str, pattern, init)
string.match() sLooks for the first match of pattern in the string. Parameter init is optional, specifies the starting point for search, default is 1 and can be negative..
When pairing successed, the capture returns all captured results; If the capture label is not set, the entire pairing string is returned. Return nil when there is no capture.
string.match("I have 2 questions for you.", "%d+ %a+")
2 questions
string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)"))
2, "questions"

Convert upper and lower case letters of string

The following example demonstrates how to convert upper and lower case letters of string:

Example:

string1 = "Lua";
print(string.upper(string1))
print(string.lower(string1))

--Execution Result:
--LUA
--lua

String lookup and inversion

The following example demonstrates how to find and reverse strings:

Example:

string = "Lua Tutorial"
-- Search String
print(string.find(string,"Tutorial"))
reversedString = string.reverse(string)
print("New string is",reversedString)

--Execution Result为:
--5    12
--New string is lairotuT auL

String formatting

Lua provides the string.format() function to generate strings in a particular format, with the format as the first argument to the function, followed by various data for each code in the format.

The format string makes the resulting long string much more readablem which is similiar to printf() in C language.
The following example demonstrates how to format a string:

The format string may contain the following escape codes:

  • %c - takes a number and converts it to the corresponding character in the ASCII code table
  • %d, % I - takes a number and converts it to a signed integer format
  • %o - takes a number and converts it to octal number format
  • %u - takes a number and converts it to unsigned integer format
  • %x - takes a number and converts it to hexadecimal number format, using lowercase letters
  • %X - takes a number and converts it to hexadecimal number format, using uppercase letters
  • %e - takes a number and converts it to scientific notation, using a lowercase e
  • %E - takes a number and converts it to a scientific notation format, using a capital E
  • %f - takes a number and converts it to floating point format
  • %g(%G)- takes a number and converts it to %e(%E, corresponding to %G) and a shorter form of %f
  • %q - takes a string and converts it to a format safe to read by the Lua compiler
  • %s - takes a string and formats it with the given arguments

To further refine the format, you can add parameters after %. The parameters are read in the following order:

  • (1) symbol: a + sign that indicates a number escape after a positive will show a positive sign. By default, only negative numbers will show signs.
  • (2) placeholder: a 0, used when the string width is specified. The default placeholder is space.
  • (3) alignment identifier: when string width is specified, right alignment is the default, and left alignment can be changed by increasing the - sign.
  • (3) width value
  • (5) decimal number/string clipping: the decimal part n increased after the width value, if followed by f(floating point escape character, such as %6.3f), set the floating point decimal number to keep only n bits, if followed by s(string escape character, such as %5.3s), set the string to display only the first n characters.

Example:

string1 = "Lua"
string2 = "Tutorial"
number1 = 10
number2 = 20
-- Basic string formatting
print(string.format("Basic string formatting %s %s",string1,string2))
-- Date formatting
date = 2; month = 1; year = 2020
print(string.format("Date formatting %02d/%02d/%03d", date, month, year))
-- Decimal formatting
print(string.format("%.4f",1/3))

--Execution Result:
--Basic string formatting Lua Tutorial
--Date formatting 02/01/2020
--0.3333

Other Example:

string.format("%c", 83)                 -- output S
string.format("%+d", 17.0)              -- output +17
string.format("%05d", 17)               -- output 00017
string.format("%o", 17)                 -- output 21
string.format("%u", 3.14)               -- output 3
string.format("%x", 13)                 -- output d
string.format("%X", 13)                 -- output D
string.format("%e", 1000)               -- output 1.000000e+03
string.format("%E", 1000)               -- output 1.000000E+03
string.format("%6.3f", 13)              -- output 13.000
string.format("%q", "One\nTwo")         -- output "One\
                                        --   Two"
string.format("%s", "monkey")           -- output monkey
string.format("%10s", "monkey")         -- output monkey
string.format("%5.3s", "monkey")        -- output  mon

Convertion between Characters and integers

Example:

-- Convert String
-- Convert the first character
print(string.byte("Lua"))
-- Convert the third character
print(string.byte("Lua",3))
-- Convert the first character in the end
print(string.byte("Lua",-1))
-- the second character
print(string.byte("Lua",2))
-- Convert the second character in the end
print(string.byte("Lua",-2))

-- Integer ASCII code converted to characters
print(string.char(97))

--Execution Result:
--76
--97
--97
--117
--117
--a

Other Common Functions

The following examples demonstrate other string executions, such as calculating string length, string concatenation, string replication, and so on:
string1 = "www."
string2 = "mini1"
string3 = ".cn"
-- use .. to connest string
print("connest string",string1..string2..string3)

-- string length
print("string length ",string.len(string2))

-- replicate string twice
repeatedString = string.rep(string2,2)
print(repeatedString)

--Execution result:
--connest string    www.miniworldgame.com
--string length     6
--mini1mini1
Last Update: 6/11/2020, 9:30:46 PM