0

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
DaEaaL
  • 3
  • 3
  • Which one is line 440? – lhf Aug 14 '14 at 22:11
  • possible duplicate of [Error while trying to call a class method: attempt to index local 'self' (a nil value) - Lua](http://stackoverflow.com/questions/7353035/error-while-trying-to-call-a-class-method-attempt-to-index-local-self-a-nil) – Tom Blodget Aug 14 '14 at 23:44

1 Answers1

0

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
Mud
  • 28,277
  • 11
  • 59
  • 92