在设计传感器设备的时候,写了很多相类似的代码,并且把处理函数和每个传感器的代码都在一起,自觉得这样子不妥。
于是考虑通过 bash 来预处理代码,把需要的代码打包到一个文件里面。
在需要插入代码的地方写关键字 include(module_name)
, 如下:
-- some lua code
include(module1)
-- other lua code
然后在bash里面实现:
- 获取
include(module_name)
的位置
get_pos() {
pos=$1
file=$2
grep -n "${pos}" ${file} | awk -F ':' '{print $1}'
}
- 获取文件的长度
get_total() {
wc -l $1 | awk '{print $1}'
}
- 删除
include(module_name)
remove_include_flag() {
typ=$1
output=$2
sed -i "/include(${typ})/d" ${output}
}
- 导入文件片段
include() {
typ=$1
part=$2
output=$3
input=${output}.1
cp ${output} ${input}
pos=$(get_pos "include(${typ})" ${input})
total=$(get_total ${input})
head -n ${pos} ${input} > ${output}
cat ${part} >> ${output}
tail -n $(((total-pos))) ${input} >> ${output}
remove_include_flag ${typ} ${output}
rm ${input}
}
- 小例子
1、创建一个 main.lua
内容如下
print('start include part')
include(part)
print('end include part')
2、创建一个 part.lua
内容如下
print('include body')
3、然后执行
mkdir dist
cp main.lua dist/main.lua
include part part.lua dist/main.lua
4、输结果 dist/main.lua
如下
print('start include part')
print('include body')
print('end include part')
网友评论