Lua 简单存取款小程序


Account = {name = "", balance = 0}

function _split(line)
  local a = line
  aa = string.find(a, " ")
  zhanghao = string.sub(a, 1, aa-1)
  a = string.sub(a, aa+1, #a)
  aa = string.find(a, " ")
  mima = string.sub(a, 1, aa-1)
  money = string.sub(a, aa+1, #a)
  return zhanghao, mima, money
end

--从file中将信息加载到table里
function load_db(record, db)
  for l in record:lines() do
    zhanghao, mima, money = _split(l)
    db[zhanghao] = mima
  end
end

--打印用户信息
function print_db(db)
  for k, v in pairs(db) do 
    print(k, v)
  end
end



function Account:new (obj)
  obj = obj or {}
  setmetatable(obj, self)
  self.__index = self
  print("开户成功!欢迎您:", self.name)
  print("账户余额:", self.balance)
  return obj
end

function Account:deposit(value) --存钱
  self.balance = self.balance + value
  print("存钱成功,账户还剩:", self.balance)
end

function Account:withdraw(value) --取钱
  if value > self.balance then
    print("没有足够的钱!")
  else 
    self.balance = self.balance - value
    print("取钱成功,账户还剩:", self.balance)
  end
end

function print_menu_01()  --打印初始菜单
  print("欢迎来到银行系统,请输入您需要办理的业务~")
  print("1---新开账户")
  print("2---退出系统")
end

function print_menu_02()  --打印登陆后的菜单
  print("请输入您需要办理的业务~")
  print("1---账户存钱")
  print("2---账户取钱")
  print("3---退出系统")
end



function main()
  record = io.open("E:/Lua/record.txt", "a")
  db = {} --存放用户信息
  db = load_db(record, db) 
  print_menu_01()
  local choice = io.read()

  if choice == "1" then
    print("请输入您的姓名")
    local tmp_name = io.read()
    print("请输入您的密码")
    local tmp_password = io.read()
    local tmp = {name = tmp_name, balance = 0}
    cur_account = Account:new(tmp)
    io.output(record)
    io.write( tmp_name .. tmp_password ..  tostring(0) .. "\n")
    io.close()
  elseif choice == "2" then
    os.exit()
  end

  while true do
    print_menu_02()
    local choice = io.read()
    if choice == "1" then
      print("请输入要存款的金额")
      local tmp_money = tonumber(io.read())      
      cur_account:deposit(tmp_money)
    elseif choice == "2" then
      print("请输入要取款的金额")
      local tmp_money = tonumber(io.read())  
      cur_account:withdraw(tmp_money)
    elseif choice == "3" then
      os.exit()
    end
  end
end

main()




猜你喜欢

转载自blog.csdn.net/u010859498/article/details/81360248