问题描述:

What I'm currently trying to do is make a table of email addresses (as keys) that hold person_records (as values). Where the person_record holds 6 or so things in it. The problem I'm getting is that when I try to assign the email address as a key to a table it complains and says table index is nil... This is what I have so far:

random_record = split(line, ",")

person_record = {first_name = random_record[1], last_name = random_record[2], email_address = random_record[3], street_address = random_record[4], city = random_record[5], state = random_record[6]}

email_table[person_record.email_address] = person_record

I wrote my own split function that basically takes a line of input and pulls out the 6 comma seperated values and stores them in a table (random_record)

I get an error when I try to say email_table[person_record.email_address] = person_record.

But when I print out person_record.email_address it's NOT nil, it prints out the string I stored in it.. I'm so confused.

function split(str, pat)

local t = {} -- NOTE: use {n = 0} in Lua-5.0

local fpat = "(.-)" .. pat

local last_end = 1

local s, e, cap = str:find(fpat, 1)

while s do

if s ~= 1 or cap ~= "" then

table.insert(t,cap)

end

last_end = e+1

s, e, cap = str:find(fpat, last_end)

end

if last_end <= #str then

cap = str:sub(last_end)

table.insert(t, cap)

end

return t

end

网友答案:

The following code is copy and pasted from your example and runs just fine:

email_table = {}
random_record = {"first", "second", "third"}
person_record = {first_name = random_record[1], last_name = random_record[1], email_address = random_record[1]}
email_table[person_record.email_address] = person_record

So your problem is in your split function.

BTW, Lua doesn't have "hashtables". It simply has "tables" which store key/value pairs. Whether these happen to use hashes or not is an implementation detail.

网友答案:

It looks like you iterating over some lines that have comma-separated data. Looking at your split function, it stops as soon as there's no more separator (,) symbols in particular line to find. So feeding it anything with less than 3 ,-separated fields (for very common example: an empty line at end of file) will produce a table that doesn't go up to [3]. Addressing any empty table value will return you a nil, so person_record.email_address will be set to nil as well on the 2nd line of your code. Then, when you attempt to use this nil stored in person_record.email_address as an index to email_table in 3rd line, you will get the exact error you've mentioned.

相关阅读:
Top