summaryrefslogtreecommitdiff
path: root/examples/resources/lib/rune.lua
blob: 5e04d8bb88dabd2534ac756c2154da5f6c7aaff8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
-- For luaJit compatibility.
if table.unpack == nil then
	table.unpack = unpack
end

local Rune = {}
local metatable = {
	__index = Rune,
	__tostring = function( r )
		return r.string
	end,
	__len = function( r )
		return RL.GetCodepointCount( r.string )
	end,
	__eq = function( r1, r2 )
		return r1.string == r2.string
	end,
	__concat = function( a, b )
		return tostring( a )..tostring( b )
	end,
}

function Rune:new( string )
	local object = setmetatable( {}, metatable )

	object.string = string or ""

	return object
end

function Rune:set( string )
	self.string = string or ""
end

function Rune:serialize()
	return "Rune:new("..self.string..")"
end

function Rune:clone()
	return Rune:new( self.string )
end

function Rune:len()
	return RL.GetCodepointCount( self.string )
end

function Rune:getCodepoints()
	return RL.LoadCodepoints( self.string )
end

function Rune:getCodepoint( index )
	local codepoint = RL.GetCodepoint( self.string, index )
	return codepoint
end

function Rune:getCodepointSize( index )
	local _, codepointSize = RL.GetCodepoint( self.string, index )
	return codepointSize
end

function Rune:insert( pos, string )
	local codepoints = self:getCodepoints()

	for i, codepoint in ipairs( RL.LoadCodepoints( string ) ) do
		table.insert( codepoints, pos + i - 1, codepoint )
	end
	self.string = RL.LoadUTF8( codepoints )
end

function Rune:sub( i, j )
	local codepoints = self:getCodepoints()
	return RL.LoadUTF8( { table.unpack( codepoints, i, j ) } )
end

function Rune:gsub( pattern, repl )
	return string.gsub( self.string, pattern, repl )
end

function Rune:split( delimiter )
	local splits = {}

	for str in string.gmatch( self.string, "([^"..delimiter.."]+)" ) do
		table.insert( splits, str )
	end

	return splits
end

return Rune