-- 字串String


-- 單引號
string1 = 'Lua' 

-- 雙引號 
string2 = "Introduction" 

print(string1, string2)

-- 中括號(主要用在跨行的長字串)

a=[[This is a very
                    very
                    very ...
                            long story.]]
print(a)

-- 用跳脫字元 \z 來串接長字串, 直接串接到下一行的非空白字元 ( \z : End of string )
a="This is a very \z
                   very \z
                   very ... \z
                          long story."
print(a)    --> 印出 This is a very very very ... long story.

print("----strings and numbers----")
local age = 12
local name = "Billy"
print(name .. " is " .. age .. " years old.")


print("----concatenate strings----")
local phrase = "My name is "
local name = "John Doe"
print(phrase .. name ..'.') -- My name is John Doe.

print("----string comparisions----")
local name = "Tom"
if name == "Billy" then --false
  print("Name is Billy.")
elseif name == "Tom" then --true
  print("Name is Tom.")
end


print("----字串長度----")
print(string.len("Hello World!"))
print(#string1)

-- 隱性型別轉換
-- 由於 Lua 是弱型態語言, 當"數值字串"進行"數值運算"時會自動"型態轉換", 例如 :
print("----字串 型態轉換----")
print("12" + 3)          --> 印出 15, 會先將字串轉成數值再相加.
print("4.5e25" * "3")    --> 印出 1.35e+026
-- 數值進行字串運算時, Lua 也會自動將數值先轉成字串再運算, 例如 :
-- .. 之間必須有一個空格
print(20 .. 15)          --> 印出 2015


-- 顯性型別轉換
-- 利用 tonumber() 與 tostring() 函式, 例如 :
print("----字串 型態轉換----")
if (tonumber("2e2") == 200) then print("match") end      --> 印出 match
if (tonumber("10.5") == 10.5) then print("match") end    --> 印出 match

-- string s repeated n times
print("----字串repeat----")
s = "12345"
n = 5
print(string.rep(s, n))


print("----字串大小寫轉換----")
print(string.upper("assSalVNDWl"))
print(string.lower("assSalVNDWl"))

-- Method 1
-- string.sub(s,i,j) extracts a piece of the string s, from the i-th to the j-th character inclusive.
print("----字串擷取----")
s = "[in brackets]"
print(string.sub(s, 5, -2))   --> 印出 brackets

-- Method 2
-- string.gmatch(inputString, regexFormat)
inputstr = "ccc\nddd\naaa\neee"
for str in string.gmatch(inputstr, "(ddd)") 
    do print(str)
end


inputstr = "cccdd..sep..aabb..sep..f"
for str in string.gmatch(inputstr, "([^\"..sep..\"]+)") do
    print(str) 
end
-- [^abc]:Any single character except: a, b, or c
-- a+:一個以上

-- Get sub-string and replase
-- string.gsub(inputString,findString,replaceString)
print("----字串置換----")
print(string.gsub("It's a cat.", "cat", "dog"))  


Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: