- ComputerCraft | Programmable Computers for Minecraft
- → Himself12794's Content
Himself12794's Content
There have been 43 items by Himself12794 (Search limited from 10-February 22)
#172567 Emailing servers
Posted by
Himself12794
on 09 April 2014 - 04:28 PM
in
Ask a Pro
#167678 Determining Prime
Posted by
Himself12794
on 10 March 2014 - 02:16 PM
in
Ask a Pro
theoriginalbit, on 10 March 2014 - 02:13 PM, said:
Himself12794, on 10 March 2014 - 07:22 AM, said:
repeat if primes(number) then count=count+1 sum=sum+number end number=number+1 until count == 1000
#167673 Determining Prime
Posted by
Himself12794
on 10 March 2014 - 02:05 PM
in
Ask a Pro
#167661 Determining Prime
Posted by
Himself12794
on 10 March 2014 - 07:22 AM
in
Ask a Pro
I know the answer should be: 3682913
But instead I'm getting: 3690837
The code I use is below.
function primes(n)
if n<2 then
return false
elseif n==2 then
return true
elseif n%2==0 or n%3==0 then
return false
else
for i=3, math.ceil(n^0.5) do
if n%i==0 then
return false
end
end
end
return true
end
local count=0
local number=2
local sum=0
while count<1000 do
if primes(number) then
count=count+1
sum=sum+number
end
number=number+1
end
print(sum)
I ran a trace and found that just one sum down, I get, 3682913, which is just 3 off. Not sure if my problem has to do with determining primes in the first place, limitations of lua, or just simple errors. Help is appreciated.
#165593 Graphic Explorer for CraftOS
Posted by
Himself12794
on 21 February 2014 - 01:04 AM
in
Operating Systems
#165414 having issues with division and floating point numbers
Posted by
Himself12794
on 19 February 2014 - 11:53 AM
in
Ask a Pro
#165360 Request for testing - HimCo Industries Experimental OS v0.8 and Network
Posted by
Himself12794
on 19 February 2014 - 01:39 AM
in
Operating Systems
Right now, all I've really done is made a master server, router, passwords server, a file server, and a nice GUI for the client computer.
All of the computers start with rednet modems on the top, since I have not done a config program yet.
The code for the master server just has to be downloaded and run on the computer.
It's found here:
http://pastebin.com/zeZyS1fd
The routers help bridge the gap when distance is too far. There has to be at least one router, as the clients will not connect to the master server. After running the router startup, just put in the id of the master server.
The code for the routers are here:
http://pastebin.com/ZZ0zdH1x
There is the password server, which is supposed to control authentication. You register the sub-servers the same way as a router.
Password server is here: (sorry for inconvenient location, ran out of pastebin pastes)
http://philip.whitin...0server/startup
You can use below to download.
You can use function download(url,file)
local content = http.get(url).readAll()
if not content then
error("Could not connect to website")
end
f = fs.open(file,'w')
f.write(content)
f.close()
end
The file server allows the client to save files remotely, where anyone can access it. Password server provides protection to user specific files.
Code is here: (again, sorry for wonky location)
http://philip.whitin...0server/startup
Finally, the client code. This one has the most files, and the one mostly likely to be littered with mistakes.
http://philip.whitin...craft/installer
That one has an installer, so you just download and run it.
I believe that's everything. If anyone is willing to try it out, I hope you are able to tell me about any errors or weak coding you find.
Thanks!
#165358 Strengthening Password Server Security
Posted by
Himself12794
on 19 February 2014 - 01:22 AM
in
Ask a Pro
Bomb Bloke, on 19 February 2014 - 01:15 AM, said:
If people can tap into them, then (properly implemented) encryption would secure things, yes - assuming they can't get direct access the server machine, in which case all bets are off unless you rig up some rather complicated security directly on that unit (along the lines of "needs a password just to boot because everything on the system is encrypted"-type-security).
The best starting point is to figure out how many people are likely to want to break into your system, and where their knowledge levels are. You merely need to aim for a level of security that, for them, would be more trouble then it's worth to break through.
That's what I'm banking on. Right now this is mostly to just to see if I can actually finish this project, and then it's mostly for convenience. Really the only reason the passwords are there right now are to give some semblance of a network, and prevent someone from deleting a file he did not upload. Later I will add instant messaging and email, and that will require a bit more of security savy. I was actually just about to put what I've done so far in the OS section to see if I could get anyone to test it for me and give feedback.
#165351 Strengthening Password Server Security
Posted by
Himself12794
on 19 February 2014 - 12:17 AM
in
Ask a Pro
CometWolf, on 19 February 2014 - 12:11 AM, said:
#165343 Strengthening Password Server Security
Posted by
Himself12794
on 18 February 2014 - 10:23 PM
in
Ask a Pro
Bomb Bloke, on 18 February 2014 - 10:16 PM, said:
Himself12794, on 18 February 2014 - 09:25 PM, said:
I could have the client require to know the parent id as well, but I'm trying to make it so I can just spread the routers out throughout the world, and have some just pop in and attempt to connect, provided they have the correct OS.
The only broadcast I have is for a computer asking to join the newtwork, then everything else is based on stored ids after initial registration. I made the master server be able to act as a router as well, but I'm debating keeping this function.
#165340 Strengthening Password Server Security
Posted by
Himself12794
on 18 February 2014 - 09:25 PM
in
Ask a Pro
I have several different computers, there's router files, a master server computer, sub-servers, and the client computer. What I'm most interested in is the password sub server and the client.
Here's the relevant client code:
rednet.open('top')
--This is a console
os.loadAPI('functions')
os.loadAPI('errors')
local function header()
term.clear()
term.setCursorPos(1,1)
print('HimCo Industries\' Experimental OS')
print()
end
local function registerComputer()
local msg=functions.ser({id=os.getComputerID(),action='registerComputer'})
rednet.broadcast(msg)
print('looking for valid router')
local id=rednet.receive(5)
if not id then
print('Could not find valid router.')
return false
end
local id,msg=functions.receiveMessage(5)
if not id then
print('No valid router found')
return false
end
print(msg)
textutils.tabulate(msg)
local values=functions.unser(msg)
if values['action']=='computerAdded' then
print('saving router id #',values['id'],' as parent router')
functions.saveToFile('parent_id',values['id'],'config')
return true
end
end
local function checkSession()
if functions.loadFromFile('session')=='Guest' then
return true
end
local msg=functions.ser({action='password_server',id=os.getComputerID(),value='session',username=functions.loadFromFile('session','config')})
functions.sendMessage(parent_id,msg)
local id,msg=functions.receiveMessage(3)
if errors.noService(id,'error') then
return 'error'
end
local values=functions.unser(msg)
if values['user_id']==os.getComputerID() then
functions.saveToFile('session',values['username'])
return true
else
return values['value']
end
end
local function login()
header()
write('Please give your username: ')
local username=read()
print()
write('Please give your password: ')
local password=read('*')
local msg=functions.ser({action='password_server',id=os.getComputerID(),value='login',password=password, username=username})
if functions.sendMessage(parent_id,msg) then
local id,msg=functions.receiveMessage(5)
if errors.noService(id) then
print('Could not connect to server. Do you want to enter offline mode?')
if functions.dichotomy('Go Offline','Quit') then
functions.saveToFile('session','Guest')
end
end
local values=functions.unser(msg)
if values['session']~=os.getComputerID() then
print('That profile is already open on computer #',values['session'],'. Please logout there, and try again.')
sleep(2)
os.reboot()
elseif values['value'] and values['session']==os.getComputerID() then
print('User ',username,' has been logged in.')
functions.saveToFile('session',username)
sleep(2)
return true
--os.reboot()
else
sleep(2)
print('Username and password combination do not match')
sleep(2)
os.reboot()
end
else
print('Could not connect to server. Do you want to enter offline mode?')
if functions.dichotomy('Go Offline','Quit') then
functions.saveToFile('session','Guest')
else
os.reboot()
end
end
end
local function registerAccount()
local password
local username
while true do
header()
write('Give a username: ')
username=read()
write('Give a password: ')
password=read('*')
write('Please confirm password: ')
local tmp=read('*')
if tmp==password then break end
print('Passwords do not match, please try again')
sleep(1.5)
end
local msg=functions.ser({action='password_server',id=os.getComputerID(),value='create',password=password,username=username})
functions.sendMessage(parent_id,msg)
local id,msg=functions.receiveMessage()
local values=functions.unser(msg)
if values['action']=='return' and values['value'] then
print('Account created.')
sleep(2)
os.reboot()
else
print('Account already exists.')
sleep(2)
os.reboot()
end
end
local function validate(parent_id)
local choices={
'Login',
'Create Account',
'Shutdown'
}
local choice=functions.multipleChoice(choices,1,2)
if not choice then
os.reboot()
end
if choice==1 then
login()
elseif choice==2 then
registerAccount()
elseif choice==3 then
os.shutdown()
end
end
functions.createFile('config')
if not functions.loadFromFile('parent_id','config') then
registerComputer()
end
parent_id=functions.loadFromFile('parent_id')
local session=checkSession()
if not session then
header()
validate(parent_id)
elseif session=='error' then
print('Could not connect to server. Do you want to enter offline mode?')
if functions.dichotomy('Go Offline','Quit') then
functions.saveToFile('session','Guest')
else
os.reboot()
end
end
shell.setDir('files')
shell.run('menu')
Here is the password server code:
os.loadAPI('functions')
rednet.open('top')
shell.run('clear')
local function header()
functions.lineClear()
functions.printCentered('This is the password server')
functions.lineClear()
print()
functions.lineClear()
print('Computer: #',os.getComputerID())
functions.lineClear()
print('Parent Computer: #',parent_id)
functions.lineClear()
print()
functions.lineClear()
print('===================================================')
functions.lineClear()
print()
end
local function getParentId()
parent_id=functions.loadFromFile('parent_id','config')
if not parent_id then
while true do
local parent_id=functions.numbersOnly('Please give the id of the parent router: ',3)
local msg=functions.ser({action='registerSubServer',id=os.getComputerID(),value='password_server'})
if functions.sendMessage(parent_id,msg) then
functions.saveToFile('parent_id',parent_id,'config')
break
else
print('The requested router could not be found. Please check its availability, or try another id.')
end
sleep(0.01)
end
end
return parent_id
end
local function manager(msg)
local values=functions.unser(msg)
functions.lineClear()
print('Received message from Computer #',values['id'])
functions.lineClear()
print('Value is ',values['value'])
local verify=false
-------------------------------------
if values['value']=='create' then
--[----------------------------------
if not functions.loadFromFile(values['username'],'passwords') then
functions.saveToFile(values['username'],values['password'],'passwords')
functions.lineClear()
print('Created account for ',values['username'])
verify=true
end
local msg=functions.ser({action='return',id=values['id'],value=verify})
functions.sendMessage(parent_id,msg)
-------------------------------------]
elseif values['value']=='login' then
--[-----------------------------------
if not functions.loadFromFile(values['username'],'sessions') then
if functions.loadFromFile(values['username'],'passwords')==values['password'] then
functions.lineClear()
print('Logging in ',values['username'])
functions.saveToFile(values['username'],values['id'],'sessions')
verify=true
end
elseif values['id']==functions.loadFromFile(values['username'],'sessions') then
verify=true
end
local msg=functions.ser({action='return',id=values['id'],value=verify,session=functions.loadFromFile(values['username'],'sessions')})
functions.sendMessage(parent_id,msg)
-------------------------------------]
elseif values['value']=='session' then
--[-----------------------------------
user_id=functions.loadFromFile(values['username'],'sessions')
verify=user_id==values['id']
local msg=functions.ser({action='return',id=values['id'],value=verify,session_id=user_id,username=values['username']})
functions.sendMessage(parent_id,msg)
functions.lineClear()
print('Send Message to ',values['id'])
--------------------------------------]
elseif values['value']=='logout' then
--[------------------------------------
if functions.loadFromFile(values['username'],'sessions')==values['id'] then
functions.lineClear()
print('Logging out ',values['username'])
functions.saveToFile(values['username'],nil,'sessions')
verify=true
end
local msg=functions.ser({action='return',id=values['id'],value=verify})
functions.sendMessage(parent_id,msg)
end
end
parent_id=getParentId()
header()
functions.createFile('config')
functions.createFile('passwords')
functions.createFile('sessions')
functions.saveToFile('Guest',false,'sessions')
parent_id=getParentId()
while true do
local id,msg=functions.receiveMessage()
manager(msg)
local x,y=term.getCursorPos()
term.setCursorPos(1,1)
header()
term.setCursorPos(x,y)
end
If necessary, the router code is here, and the master server code is here.
#165334 having issues with division and floating point numbers
Posted by
Himself12794
on 18 February 2014 - 08:51 PM
in
Ask a Pro
elseif opptype == "divide" then nst2 = table.concat(numset2) nst1 = table.concat(numset1) opt = nst1/nst1 printOut(opt)
Should be:
elseif opptype == "divide" then nst2 = table.concat(numset2) nst1 = table.concat(numset1) opt = nst1/nst2 printOut(opt)
I changed that and it seems to work.
#164704 Help with a scrolling multiple choice selection
Posted by
Himself12794
on 12 February 2014 - 11:58 PM
in
Ask a Pro
Here's the code:
local function header(banner)
term.clear()
term.setCursorPos(1,1)
print("HimCo Industries' Experimental OS")
--print(loadFromFile('session','./config'),' logged into Computer ID #',os.getComputerID())
print()
printCentered(banner)
print()
end
local function lineClear()
local _,y=term.getCursorPos()
term.clearLine()
term.setCursorPos(1,y)
end
function printCentered(str)
local termX, _termY=term.getSize()
local _cursX, cursY=term.getCursorPos()
local newX = math.ceil(termX/2)-math.ceil(string.len(str)/2)
term.setCursorPos(newX,cursY)
print(str)
end
local function multipleChoice(choices, sel,escape,delete)
local escape=escape or 'startup'
local size = #choices
local sel = sel or 1 --initial selection
local xsize,ysize=term.getSize()
local xcoord,ycoord=term.getCursorPos()
local diff=ysize-ycoord
local interval=1
while true do
term.setCursorPos(xcoord,ycoord)
if sel>diff then
interval=sel-diff+1
else
interval=1
end
for i=interval, interval+diff-1 do
lineClear()
if i == sel then
printCentered('[ '..choices[i]..' ]')
elseif i<=size then
printCentered(' '..choices[i]..' ')
end
end
--user input
local event,key=os.pullEvent('key')
if key == 208 --down arrow
or key == 31 then -- S
sel = sel+1
if sel > size then
sel = 1 --bottom reached, moving back to top
end
elseif key == 200 -- up arrow
or key == 17 then -- W
sel = sel-1
if sel < 1 then
sel = size -- top reached, moving to bottom
end
elseif key == 28 -- enter
or key == 57 then --space
return sel --input complete
elseif key == 14 then -- backspace
shell.run(escape)
shell.exit()
--os.reboot()
elseif key == 211 and delete then -- Returns true as well as selection when delete is pressed
return sel,true
end
end
end
#164701 Help with a scrolling multiple choice selection
Posted by
Himself12794
on 12 February 2014 - 11:38 PM
in
Ask a Pro
Here's the code for this:
local function multipleChoice(choices, sel,escape,delete)
local escape=escape or 'startup'
local size = #choices
local sel = sel or 1 --initial selection
local xsize,ysize=term.getSize()
local xcoord,ycoord=term.getCursorPos()
local diff=ysize-ycoord
while true do
term.setCursorPos(xcoord,ycoord)
-- if sel<=diff then
-- term.setCursorPos(xcoord,ycoord)
if sel>=diff then
for i=sel, sel+diff-1 do
lineClear()
if i == sel then
printCentered('[ '..choices[i]..' ]')
elseif i<=size then
printCentered(' '..choices[i]..' ')
else
printCentered('')
end
end
--user input
local event,key=os.pullEvent('key')
if key == 208 --down arrow
or key == 31 then -- S
sel = sel+1
if sel > size then
sel = 1 --bottom reached, moving back to top
end
elseif key == 200 -- up arrow
or key == 17 then -- W
sel = sel-1
if sel < 1 then
sel = size -- top reached, moving to bottom
end
elseif key == 28 -- enter
or key == 57 then --space
return sel --input complete
elseif key == 14 then -- backspace
shell.run(escape)
shell.exit()
--os.reboot()
elseif key == 211 and delete then -- Returns true as well as selection when delete is pressed
return sel,true
end
end
end
#164681 Help with a scrolling multiple choice selection
Posted by
Himself12794
on 12 February 2014 - 06:35 PM
in
Ask a Pro
Bomb Bloke, on 12 February 2014 - 06:09 PM, said:
if sel<=diff then
term.setCursorPos(xcoord,ycoord)
for i,v in ipairs(choices) do
lineClear()
if i == sel then
printCentered('[ '..v..' ]')
elseif i <= diff then
printCentered(' '..v..' ')
end
end
else
for i,v in ipairs(choices) do
printCentered('')
end
local over=diff-sel
term.setCursorPos(xcoord,ycoord)
for i,v in ipairs(choices) do
lineClear()
if i == sel then
printCentered('[ '..v..' ]')
elseif i >= sel+over then
printCentered(' '..v..' ')
end
end
end... you may want something like this:
term.setCursorPos(xcoord,ycoord)
local start = math.floor(sel / diff) * diff
for i=start+1,start+diff do
lineClear()
if i <= size then
if i == sel then
printCentered('[ '..choices[i]..' ]')
elseif i <= diff then
printCentered(' '..choices[i]..' ')
end
end
endAlso, the keys API is worth a look. It allows you to rewrite stuff like this:
if key == 208 --down arrow or key == 31 then -- S
... like this:
if key == keys.down or key == keys.s then
Using these pre-defined constant variables stored in that API means you don't need to work out the numeric codes yourself.
#164676 Help with a scrolling multiple choice selection
Posted by
Himself12794
on 12 February 2014 - 05:35 PM
in
Ask a Pro
Here's the code:
local function header(banner)
term.clear()
term.setCursorPos(1,1)
print("HimCo Industries' Experimental OS")
--print(loadFromFile('session','./config'),' logged into Computer ID #',os.getComputerID())
print()
printCentered(banner)
print()
end
local function lineClear()
local _,y=term.getCursorPos()
term.clearLine()
term.setCursorPos(1,y)
end
function printCentered(str)
local termX, _termY=term.getSize()
local _cursX, cursY=term.getCursorPos()
local newX = math.ceil(termX/2)-math.ceil(string.len(str)/2)
term.setCursorPos(newX,cursY)
print(str)
end
local function multipleChoice(choices, sel,escape,delete)
local shiftList=false
local escape=escape or 'startup'
local size = #choices
local sel = sel or 1 --initial selection
local xsize,ysize=term.getSize()
local xcoord,ycoord=term.getCursorPos()
local diff=ysize-ycoord
if diff>#choices then
shiftList=true
end
while true do
if sel<=diff then
term.setCursorPos(xcoord,ycoord)
for i,v in ipairs(choices) do
lineClear()
if i == sel then
printCentered('[ '..v..' ]')
elseif i <= diff then
printCentered(' '..v..' ')
end
end
else
for i,v in ipairs(choices) do
printCentered('')
end
local over=diff-sel
term.setCursorPos(xcoord,ycoord)
for i,v in ipairs(choices) do
lineClear()
if i == sel then
printCentered('[ '..v..' ]')
elseif i >= sel+over then
printCentered(' '..v..' ')
end
end
end
--user input
local event,key=os.pullEvent('key')
if key == 208 --down arrow
or key == 31 then -- S
sel = sel+1
if sel > size then
sel = 1 --bottom reached, moving back to top
end
elseif key == 200 -- up arrow
or key == 17 then -- W
sel = sel-1
if sel < 1 then
sel = size -- top reached, moving to bottom
end
elseif key == 28 -- enter
or key == 57 then --space
return sel --input complete
elseif key == 14 then -- backspace
shell.run(escape)
shell.exit()
--os.reboot()
elseif key == 211 and delete then -- Returns true as well as selection when delete is pressed
return sel,true
end
end
end
header('What?')
choices={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','aa','ab','ac','ad','ae','af'}
choice=multipleChoice(choices)
#164554 Weird Text Utilities + script error
Posted by
Himself12794
on 11 February 2014 - 10:01 PM
in
Ask a Pro
#164550 Weird Text Utilities + script error
Posted by
Himself12794
on 11 February 2014 - 09:47 PM
in
Ask a Pro
Here's the code:
rednet.open('top')
print('This is computer #',os.getComputerID())
print('This is the password server')
local function numbersOnly(pre,limit)-- Works like read(), except only accepts numbers. Writes a desired prefix and can accept a max number length
term.setCursorBlink(true)
local x,y=term.getCursorPos()
local num=''
while true do
if pre then write(pre) end
write(num)
local event,key=os.pullEvent()
if event=='char' and tonumber(key) then
if #num<limit then
num=num..key
end
elseif event=='key' then
if key==14 then
num=string.sub(num, 1, -2)
elseif key==28 then
print()
term.setCursorBlink(false)
return tonumber(num)
end
end
term.setCursorPos(x,y)
term.clearLine()
end
end
local function checkId(id)--Checks for id in file id, returns true if present, false if not
if fs.exists("ids") then
local f = fs.open("ids", "r")
for line in f.readLine do
if line:find(id) then
return true
end
end
return false
end
end
local function saveId(id)-- Saves an id to file id
if not checkId(id) then
local f=fs.open('ids','a')
f.writeLine(id..'')
f.close()
return true
else
return false
end
end
local function receiveMessage()-- Same as rednet.receive(), but returns true if sending was successful, false if not
local id,msg,d=rednet.receive()
rednet.send(id,true)
return id,msg,d
end
local function sendMessage(id,msg)-- Same as rednet.send(), but sends confirmation of received message
rednet.send(id,msg,5)
local tid,tmsg,td=rednet.receive(5)
if tid==id and tmsg then
return true
else
return false
end
end
local function createFile(name)--Creates a file with filename 'name'
if not fs.exists(name) then
f=fs.open(name,'w')
f.writeLine('{}')
f.close()
end
end
local function checkId(id)
if fs.exists("ids") then
local f = fs.open("ids", "r")
for line in f.readLine do
if line:find(id) then
return true
end
end
return false
end
end
local function saveId(id)
if not checkId(id) then
local f=fs.open('ids','a')
f.writeLine(id..'')
f.close()
return true
else
return false
end
end
local function loadFromFile(variable,file)
local file_path=fs.open(file,'r')
local values=textutils.unserialize(file_path.readLine())
for i,v in pairs(values) do
if i==variable then
file_path.close()
return v
end
end
file_path.close()
return nil
end
local function saveToFile(variable,value,file)
local file=file or 'config'
createFile(file)
local file_path=fs.open(file,'r')
local values=textutils.unserialize(file_path.readLine())
values[variable]=value
file_path.close()
local file_path=fs.open(file,'w')
file_path.writeLine(textutils.serialize(values))
file_path.close()
end
local function getParentId()
parent_id=loadFromFile('parent_id','config')
if not parent_id then
while true do
local parent_id=numbersOnly('Please give the id of the parent router: ',3)
local msg=textutils.serialize({action='registerSubServer',id=os.getComputerID(),value='password_server'})
if sendMessage(parent_id,msg) then
saveToFile('parent_id',parent_id,'config')
break
else
print('The requested router could not be found. Please check its availability, or try another id.')
end
sleep(0.01)
end
end
return parent_id
end
local function manager(msg)
print('da heck?')
local values=textutils.unserialize(msg)
print('unserialized')
print('Value is ',values['value'])
-- for i,v in pairs(values) do
-- print(i,' ',v)
-- end
local verify=false
if values['value']=='create' then
saveToFile(values['username'],values['password'],'passwords')
print('Created account for ',values['username'])
elseif values['value']=='verify' then
if loadFromFile(values['username'],'passwords')==values['password'] then
verify=true
end
local msg=textutils.serialize({action='return',id=values['id'],value=verify})
sendMessage(parent_id,msg)
end
end
createFile('config')
createFile('passwords')
local parent_id=getParentId()
while true do
local id,msg=receiveMessage
print('got message')
manager(msg)
end
Edit:
Woops, nevermind, I found it. Somehow the parenthesis at the end of 'receiveMessage()' were somehow deleted.
#163995 Concurrency, apis
Posted by
Himself12794
on 07 February 2014 - 01:04 AM
in
Ask a Pro
It's much easier I believe than messing with parallel.waitForAny()
#163993 Help (again) cleaning up a code
Posted by
Himself12794
on 07 February 2014 - 12:55 AM
in
Ask a Pro
#163990 Help (again) cleaning up a code
Posted by
Himself12794
on 07 February 2014 - 12:45 AM
in
Ask a Pro
theoriginalbit, on 07 February 2014 - 12:15 AM, said:
#1 is localising your variables
#2 your for loops
local i=1 for i, 16 do count=count+turtle.getItemCount(i4) endsince you do not use i outside the for loop once it is complete there is no need to perform a forward declaration. if you do it like so
for i = 1, 16 do count=count+turtle.getItemCount(i4) endi is localised to the for loop.
#3 This
if dichotomy('Yes','No') then
diggingMode=true
else
diggingMode=false
end
can simply be thisdiggingMode = dichotomy('Yes', 'No')
conditionals are booleans, so why test a conditional to then assign a boolean, its just waste of a fork and CPU cycles.#4 while waiting for the user to input items you can actually wait for the turtle_inventory event (assuming you're using CC 1.55 or above)
#5 these
if event=="key" and key==203 then sel=not sel end if event=="key" and key==205 then sel=not sel end if event=="key" and key==28 then break endcould actually just be
if event == "key" then if key == 203 or key == 205 then sel = not sel else if key == 28 then break end endthis reduces the amount of conditionals that need to be evaluated by removing unnecessary event checking.
EDIT: Found another one
#6 this
if casings>34 and heat>3880 then
write(3880)
write(' K')
write(' Too many casings! Only 34!')
elseif casings>34 and heat<=3880 then
write(heat)
write(' K')
write(' Too many casings! Only 34!')
elseif casings<34 then
write(heat)
write(' K')
write(' Not enough casings! 34 Needed!')
else
write(heat)
write(' K')
end
can be simplified to the followingwrite(math.min(heat, 3880)..' K')
if casings > 34 then
write(' Too many casings! Only 34!')
elseif casings < 34 then
write(' Not enough casings! 34 Needed!')
end
Also, is there a way I can do the program without having to declare this twice?
local count={
standard=turtle.getItemCount(1),
reinforced=turtle.getItemCount(2),
advanced=turtle.getItemCount(3),
lava=turtle.getItemCount(4)+turtle.getItemCount(5)==2,
nichrome=turtle.getItemCount(6)>=4,
kanthal=turtle.getItemCount(7)>=4
}
I tried passing it out of the function like I did with heat, but it did not work, even when I removed the local statement from in front of it.
#163971 Help with a mining machine.
Posted by
Himself12794
on 06 February 2014 - 10:57 PM
in
Ask a Pro
#163968 Updating information
Posted by
Himself12794
on 06 February 2014 - 10:54 PM
in
Ask a Pro
eu = p.getEUOutput()in your while loop, right at the beginning. If you don't do that, then eu will always be what it was when you started the program. Adding to the while loop allows it to constantly update.
#163962 Help (again) cleaning up a code
Posted by
Himself12794
on 06 February 2014 - 10:33 PM
in
Ask a Pro
The reason I always ask is because all of my coding is self-taught and I have no idea what a professional code should look like.
Here's the code, which gathers the information needed for constructing an Industrial Blast Furnace:
local diggingMode = false
local function lineClear()
x,y=term.getCursorPos()
term.clearLine()
term.setCursorPos(1,y)
end
local function dichotomy(a,B)/> --Gives a selection of two choices, a or b, returning true for a and false for b
sel=true
while true do
if sel then
write("--> "..a.." "..B)/>
else
write(" "..a.." --> "..B)/>
end
event,key=os.pullEvent()
if event=="key" and key==203 then sel=not sel end
if event=="key" and key==205 then sel=not sel end
if event=="key" and key==28 then break end
sleep(0.01)
lineClear()
end
print()
return sel
end
local function enableDiggingMode()-- Asks to enable digging mode
print('Do you wish to enable digging mode?')
print('If you do so, the turtle will clear a 3x3x4 area for the casing.')
print('Turtle with digging tool required. (Obviously)')
print()
print('Enable digging mode?')
if dichotomy('Yes','No') then
diggingMode=true
else
diggingMode=false
end
end
local function placeSlot(side,slot,wait)--Places the items in slot 'slot' on side 'side', and will wait for an item to be available if wait is true, otherwise does not check availability
if turtle.getItemCount(slot)==0 and wait then
print('Insufficient resources to complete build. Please place an item in slot '..tostring(slot))
while turtle.getItemCount(slot)==0 do
sleep(0.01)
end
end
turtle.select(slot)
placeSide(side)
end
local function placeSide(side)-- Places a block on side left, right, or back
if not side then
turtle.place()
elseif side=='left' then
turtle.turnLeft()
turtle.place()
turtle.turnRight()
elseif side=='right' then
turtle.turnRight()
turtle.place()
turtle.turnLeft()
elseif side=='back' then
turtle.turnRight()
turtle.turnRight()
turtle.place()
turtle.turnLeft()
turtle.turnLeft()
end
end
local function countResources()--Counts turtle inventory items
local count=0
local i=1
for i, 16 do
count=count+turtle.getItemCount(i4)
end
return count
end
local function keyToContinue()--Stalls the screen until a key is pressed
write('Press any key to continue')
_=os.pullEvent('key')
lineClear()
end
local function calculateHeat()--Gets the projected heat of Blast Furnace Based on configuration of different casings and upgrades in turtle inventory
local value={
standard=30,
reinforced=50,
advanced=70,
extraneous=500
}
while true do
os.startTimer(0.05)
local event,key=os.pullEvent()
if event=='timer' then
local count={
standard=turtle.getItemCount(1),
reinforced=turtle.getItemCount(2),
advanced=turtle.getItemCount(3),
lava=turtle.getItemCount(4)+turtle.getItemCount(5)==2,
nichrome=turtle.getItemCount(6)>=4,
kanthal=turtle.getItemCount(7)>=4
}
local casings=count['standard']+count['reinforced']+count['advanced']
if count['lava'] then count['lava']=1 else count['lava']=0 end
if count['nichrome'] then count['nichrome']=1 else count['nichrome']=0 end
if count['kanthal'] then count['kanthal']=1 else count['kanthal']=0 end
local requiredHeat=(value['standard']*count['standard'])+(value['reinforced']*count['reinforced'])+(value['advanced']*count['advanced'])
local extraneousHeat=(count['lava']*value['extraneous'])+(count['nichrome']*value['extraneous'])+(count['kanthal']*value['extraneous'])
heat=requiredHeat+extraneousHeat
lineClear()
if casings>34 and heat>3880 then
write(3880)
write(' K')
write(' Too many casings! Only 34!')
elseif casings>34 and heat<=3880 then
write(heat)
write(' K')
write(' Too many casings! Only 34!')
elseif casings<34 then
write(heat)
write(' K')
write(' Not enough casings! 34 Needed!')
else
write(heat)
write(' K')
end
elseif event=='key' then
return heat
end
end
end
local function info()--Gives basic overview of requirements and upgrades for the Industrial Blast Furnace
term.clear()
term.setCursorPos(1,1)
enableDiggingMode()
term.clear()
term.setCursorPos(1,1)
print('In an industrial blast furnace, the temperature is based on the type of machine casings you use, if you have heating coil upgrades and what type are they, and if you have lava in the middle.')
print()
print('The furnace requires 34 machine casings to complete. Heating coil upgrades are not required and can be added later. '..
'Lava neither is required, but is highly recommended.')
keyToContinue()
term.clear()
term.setCursorPos(1,1)
write('Put standard casings in slot 1, reinforced in 2, and advanced in 3. '..
'Place lava in slots 4 & 5. For nichrome coil upgrades, place 4 in '..
'slot 6. For kanthal coil upgrades, place 4 in slot 7. Finally, place the Industrial Blast Furnace block in slot 8\n\n'..
'The heat is calculated below:')
term.setCursorPos(1,13)
--write('Note: Max heat is 3880, although there is no reason for the heat to be any more than 3000 K.\n')
write('Press any key to continue')
term.setCursorPos(1,10)
local heat,count=calculateHeat()
--os.reboot()
--print('Note: Max heat is 3880, although there is no reason for the heat to be any more than 3000 K.')
return heat
end
local function beginAction(heat)--Looks at the heat and item count, and determines if construction can begin, and gives choice to start regardless of resource availability
term.clear()
term.setCursorPos(1,1)
local count={
standard=turtle.getItemCount(1),
reinforced=turtle.getItemCount(2),
advanced=turtle.getItemCount(3),
lava=turtle.getItemCount(4)+turtle.getItemCount(5)==2,
nichrome=turtle.getItemCount(6)>=4,
kanthal=turtle.getItemCount(7)>=4
}
local casings=count['standard']+count['reinforced']+count['advanced']
write('Construction will begin with '..count['standard']..' standard casings, '..count['reinforced']..' reinforced, '..
count['advanced']..' advanced casings, ')
if count['nichrome'] then write('nichrome coil upgrades, ') end
if count['kanthal'] then write('kanthal coil upgrades, ') end
if count['lava'] then write('and lava,') else write('and no lava,') end
write(' with a heat of '..tostring(heat)..' K.')
print()
print()
if casings>34 or countResources()<35 then
print('There is a discrepency in the number of required materials.')
print()
print('Continue anyway?')
if dichotomy('Continue','Quit') then
print('Construction will begin')
sleep(1.5)
term.clear()
term.setCursorPos(1,1)
else
os.reboot()
end
else
print('Begin contruction?')
if dichotomy('Yes','Quit') then
print()
print('Construction will begin')
sleep(1.5)
term.clear()
term.setCursorPos(1,1)
else
os.reboot()
end
end
end
local heat=info()
--term.clear()
--term.setCursorPos(1,1)
--print(heat)
--textutils.tabulate(count)
beginAction(heat)
Most of my focus is on making the code shorter and simpler, but input on code organization is fully welcome as well.
Hopefully, based on the repeated input I get, I'll need less and less help, and perhaps can provide some of my own.
Thanks in advance!
#163612 Add blinking cursor to a numbers only input function
Posted by
Himself12794
on 05 February 2014 - 01:45 AM
in
Ask a Pro
theoriginalbit, on 05 February 2014 - 01:30 AM, said:
Himself12794, on 05 February 2014 - 01:29 AM, said:
local function numbersOnly(pre)
term.setCursorBlink(true)
local x,y=term.getCursorPos()
local num=''
while true do
if pre then write(pre) end
write(num)
local event,key=os.pullEvent()
if event=='char' and tonumber(key) then
num=num..key
elseif event=='key' then
if key==14 then
num=string.sub(num, 1, -2)
elseif key==28 then
print()
term.setCursorBlink(false)
return tonumber(num)
end
end
term.setCursorPos(x,y)
term.clearLine()
end
end
Thanks for all the help!
- ComputerCraft | Programmable Computers for Minecraft
- → Himself12794's Content


