Game Development Reference
In-Depth Information
Alternatively, we can have the function work in an object-oriented manner, where we can directly
invoke the function as part of the string namespace, like so:
tString="hello how are you?"
tString:title_case()
To achieve that, we need to declare the function as follows:
function string:title_case()
return (self:gsub("^%a", string.upper):gsub("%s+%a", string.upper))
end
Padding a String
While working with text, sometimes text needs to be padded. This function helps to create strings of
a particular length by padding them:
function pad(s, width, padder)
padder=string.rep(padder or " ", math.abs(width))
if width<0 then return string.sub(padder .. s, width) end
return string.sub(s .. padder, 1, width)
end
This function caters for both left and right padding. For padding on the left, we just need to pass it a
negative length, as in the second example in the following code:
print(pad("hello",20))
print(pad("hello",-10,"0"))
CSV Functionality
While creating a game, there might be a need to save data in CSV (comma-separated value) format,
in which the data is stored as a long string of values separated by commas. CSV functions can help
you convert tables to and from CSV format.
Converting a CSV String to a Table
This first example parses and converts a CSV-formatted string into a table:
-- Convert from CSV string to table (converts a single line of a CSV file)
function fromCSV (s)
s=s .. ',' -- ending comma
local t = {} -- table to collect fields
local fieldstart=1
repeat
-- next field is quoted? (start with `"'?)
if string.find(s, '^"', fieldstart) then
local a, c
local i = fieldstart
repeat
-- find closing quote
a, i, c=string.find(s, '"("?)', i+1)
 
Search WWH ::




Custom Search