This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
roger109z's profile picture

Periods in function names?

Started by roger109z, 30 January 2017 - 04:15 AM
roger109z #1
Posted 30 January 2017 - 05:15 AM
are you able to use periods in function names?
so

local function test.read()
  doSomething()
end
would throw an error something along the lines of
bios.lua:14: [string "code"]:1: '(' expected
is there a way around this w/o excluding the period? or nah?
Dog #2
Posted 30 January 2017 - 06:28 AM
I think what you're looking for is

local test = { }
test.read = function()
  --# do something
end
Edited on 30 January 2017 - 05:30 AM
Lupus590 #3
Posted 30 January 2017 - 09:06 AM
Kind of hinted at by Dog but I'll put it clearly (if I'm able to):
. (dots/periods) are used by Lua to index tables. Using Dogs example, look up the index read in the table test and assign a function.
In your example, you have not created a table but have defined a function with the same 'name'. Lua says that any variable with a dot after it must be a table being indexed by the value after the dot, and attempts to do so when you defined test.read and failed to find a variable with the name test. This is masked by the error you got reported because you've told Lua you will be defining a function so when it sees the dot it realises that a dot is not meant to be there and so errors saying expected bracket. If you're wondering "but there is a bracket" then that's because Lua didn't get to the bracket before it errored.
Exerro #4
Posted 30 January 2017 - 09:48 PM
I think what you're looking for is

local test = { }
test.read = function()
  --# do something
end

Also the following.

local test = {}
function test.read()
    --# do something
end
It looks a bit nicer imo, and is closer to what you wrote yourself.

What's actually going on here is you're defining an index in the 'test' table. If you put a 'local' at the start, what would that mean? How can an index be local? Only the table containing the function can be local, hence the 'local test = {}' in mine and BombBloke's code examples.
roger109z #5
Posted 31 January 2017 - 12:17 AM
I didn't realize you could put functions inside of tables thanks everyone!
Exerro #6
Posted 31 January 2017 - 05:17 PM
You can put anything inside tables. You can even use functions as keys…

local function f() end
local t = {}
 
t[f] = "f"
t[error] = "error"

print( t[f] ) --#> f
print( t[error] ) --#> error