跳到主內容

【Lua】【型別】 字串- 數字

  • nil
  • boolean
  • number
  • string
  • function
  • userdata
  • thread
  • table

Number( 數字)

字串轉數字

tonumber("1.0")

數字轉字串

tostring(1.0)

自動轉型

-- Lua會自動轉型,如果一個字串與數字相加,會嘗試將字串轉換為數字
"1.0" + 2 -- => 3.0

-- 如果一個數字和字串使用串接,會嘗試將數字轉換成字串:
"1.0"..2 -- => 1.02
-- 數字轉字串
1.0 .. ""

-- 字串轉數字
1.0 + 0 

string (字串)

使用單引號或雙引號包起來:

-- 單行
s1 = 'string'
s2 = "string"

-- 多行
s3 = [[
multiple
string
]]

字串長度

-- #
print(#"abc") -- => 3

-- string.len()
rint(string.len("abc")) -- => 3

-- 文字會有些不同
-- note: with UTF-8
print(string.len("我")) -- equal print(#"我") => 3

local utf8 = require "utf8"
print(utf8.len("你好,世界!")) -- => 6

 文字串接

-- 使用兩個點 .
print("Hello, " .. "World")  -- Hello, World

-- 多文字串接建議使用table.concat

local strs = {"Hello"," ","World"}
print(table.concat(strs,""))  -- Hello, World
-- format
local string = require "string"
print(string.format("%s !! %s","Hello","World")) -- > Hello !! World

 

file的資料型態--userdata

do
  local f <close> = io.open("text.txt",'w')
  print(type(f)) -- Output: userdata
end