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

Making programs inside a program

Started by nikolay04, 31 January 2017 - 06:07 PM
nikolay04 #1
Posted 31 January 2017 - 07:07 PM
I want to know how to make a program thats writes another program. How do i do this
KingofGamesYami #2
Posted 31 January 2017 - 07:44 PM
Look into the fs API and possibly string manipulation. Why do you want to do this anyway?
Exerro #3
Posted 31 January 2017 - 11:21 PM
It depends on the complexity on the program you're creating. I'm assuming you'll be giving it some form of input, but what input will it have? What kinds of things is it expected to create?
HaddockDev #4
Posted 02 February 2017 - 08:02 PM
A good idea if your making a program is to use [[ and ]] for multi line strings(?).
If you need to supply some custom variables (maybe iteration of program) a good idea is to concatenate your variable to the start.
Here's a sample program you could hack on:

local code = [[
print("This is program number " .. n .. "!") --Notice the absence of n being defined.
]]
write("How many programs do you want to make? ")
inp = read()
amount = tonumber(inp)
if inp == nil then --Check if its actually a number
  error("Not a number")
end
for i=1,amount do --basically for(int i = 0; i < amount; i++) for some languages
  print("Program " .. i)
  local h = fs.open("program" .. i, "w") --open file in write mode
  h.write("local n = " .. i .. "\n") --add the n variable
  h.write(code) --write our code
  h.close() --close the file
end

If you run it, and give it say 5 programs to make, run one of them and it should output "This is program number <number>!"