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

Make a function callable from string (string:customFunction())

Started by ItsRodrick, 05 July 2015 - 09:06 PM
ItsRodrick #1
Posted 05 July 2015 - 11:06 PM
Hello. I've been trying to add a custom function to the string API, to be able to call myString:foo(). I did:
str = "Hello"

function string.foo(str, add)
  return str.." "..add
end

str:foo("world")

But it returns attempt to call nil. The strange thing is that I tried it in Lua for Windows, and it worked. Is it a LuaJ bug? If yes, how can I do it in CC? Because the String API works…

Thanks!
MKlegoman357 #2
Posted 05 July 2015 - 11:22 PM
You may classify it as a bug of CC, not LuaJ, but it's actually a restriction. Because there is only one LuaVM running all computers the Lua environment between them is shared. That means the string metatable is shared too, thus it is considered malicious (as you may override some functions to crash or do bad stuff to all the other computers). In the latest CC versions the string metatable is being protected and you cannot access it, nor somehow add new functions. Something interesting I found was that the first computer to load after a world load gets the original string library, thus gaining access to the string metatable.
Bomb Bloke #3
Posted 06 July 2015 - 12:33 AM
There was a discussion on the matter recently: http://www.computercraft.info/forums2/index.php?/topic/23791-string-colon-operator-problem/