'Unable to print a function's parameter outside function even when returned
Contents is a table which is passed as a parameter for the function func. The issue is that I'm unable to print out any value from the table contents. For example here you can see I was trying to print the 2nd value in the table contents but I get this error 12: attempt to index global 'contents' (a nil value)
function func(contents)
print(contents[1])
return contents
end
func({"content1", "content2", "content3"})
print(contents[2])
Solution 1:[1]
If your function will always use the global variable, create the global variable and don't take it as an argument to the function:
contents = {"content1", "content2", "content3"}
function func()
print(contents[1])
print(#contents)
return contents
end
func()
print(contents[2])
If you do want to have a global variables, I'd suggest renaming your argument to avoid confusion. As this seems to just be a sample and your table seems to contain strings, I'll rename the argument 'strings' and show you can use the return value or the global variable (repl.it):
contents = {"content1", "content2", "content3"}
function func(strings)
print(strings[1])
print(#strings)
return strings
end
local result = func(contents)
print(contents[2])
print(result[2])
Using global variables is frowned upon, you can make it local to your module and use it anywhere in your module by putting 'local' in front:
local contents = {"content1", "content2", "content3"}
Solution 2:[2]
It is because you have the print(contents[2]) outside of the function. contents is local to the function only. According to the rest of the program contents does not exist thus it is throwing an error. There is no global variable contents and it is saying 12: which tells you the error is on line 12, which again, has the print(contents[2])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jason Goemaat |
| Solution 2 | ConnerWithAnE |
