练习17.1
-- 文件名 list.lua
local list = {}
function new()
return {first = 0, last = -1}
end
list.constant = "这是一个常量"
list.new = new
function list.pushFirst(list,value)
local first = list.first - 1
list.first = first
list[first] = value
end
function list.pushLast(list,value)
local last = list.last + 1
list.last = last
list[last] = value
end
function list.popFirst(list)
local first = list.first
if first > list.last then
print("list is empty")
return 0
end
local value = list[first]
list[first] = nil
list.first = first + 1
return value
end
function list.popLast(list)
local last = list.last
if list.first > last then
print("list is empty")
return 0
end
local value = list[last]
list[last] = nil
list.last = last - 1
return value
end
return list
local list = require("list")
local mylist = list.new()
print(mylist.last)
print(list.constant)
--1
--这是一个常量
练习17.2
local temp = {}
temp.constant = "这是一个常量"
function temp.disk(cx,cy,r)
return function(x,y)
return (x-cx)^2+(y-cy)^2<=r^2
end
end
function temp.rect(left,right,bottom,up)
return function(x,y)
return left<=x and x<=right and bottom<=y and y<=up
end
end
function temp.complement(r)
return function(x,y)
return not r(x,y)
end
end
function temp.union(r1,r2)
return function(x,y)
return r1(x,y) or r2(x,y)
end
end
function temp.intersection(r1,r2)
return function(x,y)
return r1(x,y) and r2(x,y)
end
end
function temp.difference(r1,r2)
return function(x,y)
return r1(x,y) and not r2(x,y)
end
end
function temp.translate(r,dx,dy)
return function(x,y)
return r(x+dx,y+dy)
end
end
return temp
local temp = require("temp")
print(temp.constant) -->这是一个常量
练习17.3
require 用于搜索 Lua 文件的路径是存放在全局变量 package.path 中,当 Lua 启动后,会以环境变量 LUA_PATH 的值来初始这个环境变量。如果没有找到该环境变量,则使用一个编译时定义的默认路径来初始化。
假设 package.path 的值是:
/Users/dengjoe/lua/?.lua;./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua
那么调用 require(“module”) 时就会尝试打开以下文件目录去搜索目标。
/Users/dengjoe/lua/module.lua; ./module.lua /usr/local/share/lua/5.1/module.lua /usr/local/share/lua/5.1/module/init.lua /usr/local/lib/lua/5.1/module.lua /usr/local/lib/lua/5.1/module/init.lua
如果没有包含问号的组成部分,毫无疑问搜索范围会小很多,如果模块放的稍微不好,就没法找到了,大大降低了效率。



