DaEaaL
DaEaaL

Reputation: 3

Lua - util_server.lua:440 attempt to index local 'self' (a nil value)

Good evening Will you help me solve this problem?

ERROR: race/util_server.lua:440: attempt to index local 'self' (a nil value)

 
function string:split(separator)
    if separator == '.' then
        separator = '%.'
    end
    local result = {}
    for part in self:gmatch('(.-)' .. separator) do
        result[#result+1] = part
    end
    result[#result+1] = self:match('.*' .. separator .. '(.*)$') or self
    return result
end

Upvotes: 0

Views: 1060

Answers (1)

Mud
Mud

Reputation: 28991

You're probably calling it wrong.

function string:split(separator)

Is short hand for:

function string.split(self, separator)

Given a string and separator:

 s = 'This is a test'
 separator = ' '

You need to call it like this:

 string.split(s, separator)

Or:

 s:split(separator)

If you call it like this:

 s.split(separator)

You're failing to provide a value for the self argument.


Side note, you can write split more simply like this:

function string:split(separators)
    local result = {}
    for part in self:gmatch('[^'..separators..']+') do
        result[#result + 1] = part
    end
    return result
end

This has the disadvantage that you can't used multi-character strings as delimiters, but the advantage that you can specify more than one delimiter. For instance, you could strip all the punctuation from a sentence and grab just the words:

s = 'This is an example: homemade, freshly-baked pies are delicious!'
for _,word in pairs(s:split(' :.,!-')) do
    print(word)
end

Output:

This
is
an
example
homemade
freshly
baked
pies
are
delicious

Upvotes: 0

Related Questions