Jump to content

User:OrenBochman/Lua Strings

From Meta, a Wikimedia project coordination wiki

Basic String Operations

[edit]

Getting a string's length

[edit]
s = 'hello'
return #s -- returns 5

Getting a substring

[edit]
s = 'hello'
return s:sub(2, 3) -- returns 'el'
return s:sub(2) -- returns 'ello'
return s:sub(-2) -- returns 'lo'


String Operations

[edit]

basic oprations are

  • sub(star,end) string
  • find(string,text) or
  • find(string,text,offset) to start at an offset


s = "hello world"
i, j = string.find(s, "hello")
print(i, j)                      --> 1    5
print(string.sub(s, i, j))       --> hello
print(string.find(s, "world"))   --> 7    11
i, j = string.find(s, "l")   
print(i, j)                      --> 3    3
print(string.find(s, "lll"))     --> nil


local t = {} -- table to store the indices
local i = 0
while true do
    i = string.find(s, "\n", i+1) -- find 'next' newline
    if i == nil then break end
    table.insert(t, i)
end
  • use string.gsub(string,find,replace) to replace substrings or
  • use string.gsub(string,find,replace,num) to replace substrings just a number or times
s = string.gsub("Lua is cute", "cute", "great")
print(s)         --> Lua is great
s = string.gsub("abracadabra", "ab", "il", 1)
print(s)          --> ilracadabra
s = string.gsub("abracadabra", "ab", "il", 2)
print(s)          --> ilracadilra